Databases reference

You can use the Data API clients, HTTP, and the Astra CLI to perform certain administrative operations on your Astra DB Serverless databases and keyspaces.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

To perform administrative operations, the Data API clients use specific classes:

  • The Astra DB Admin class works at the level of databases, such as to create a database.

  • The Database Admin class works within a specific database, such as to create a keyspace.

For broader administration, such as user management, use the Astra Portal or the DevOps API.

Prerequisites

To perform database operations, you need a token with permission to create and configure databases, such as the Organization Administrator role.

Get an Astra DB Admin

You use the Astra DB Admin object to work at the database level. You need a client instance to create the Astra DB Admin.

The resulting object name varies by client language. For Python and Java, it is AstraDBAdmin. For TypeScript, it is AstraAdmin.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

Use client, a DataAPIClient instance, to get an AstraDBAdmin object that uses the client’s token:

admin = client.get_admin()

Parameters:

Name Type Summary

token

Optional[str]

If supplied, is passed to the Astra DB Admin instead of the client token. This may be useful when switching to a more powerful, admin-capable permission set.

Returns:

AstraDBAdmin - An object used for database-level administrative tasks.

Example response
AstraDBAdmin("AstraCS:aAbB...")

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()
databases = admin.list_databases()
new_db_admin = admin.create_database(
    "the_other_database",
    cloud_provider="AWS",
    region="eu-west-1",
)
new_db_admin.list_keyspaces()
# ['default_keyspace', 'that_other_one']

For more information, see the Client reference.

Use client, a DataAPIClient instance, to get an AstraAdmin object that uses the client’s token:

const admin = client.admin();

Parameters:

Name Type Summary

options?

AdminSpawnOptions

The options to use for the admin

Options (AdminSpawnOptions):

Name Type Summary

adminToken?

string

Application token, in the form of 'AstraCS:…​', to use for the admin. The default is the client’s token.

monitorCommands?

boolean

Whether to monitor admin commands through AdminCommandEvents, using the client as an event emitter. Defaults to false.

endpointUrl?

string

Base URL for the DevOps API

Returns:

AstraAdmin - An object used for database-management-level administrative tasks.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

const client = new DataAPIClient('TOKEN');

// Spawn an AstraAdmin instance
const admin = client.admin();

(async function () {
  // List all non-terminated databases
  console.log(await admin.listDatabases());

  // Create an actual new database
  const newDbAdmin = await admin.createDatabase({
    name: 'the_other_database',
    cloudProvider: 'aws',
    region: 'eu-west-1',
  });

  // Prints ['default_keyspace']
  console.log(await newDbAdmin.listKeyspaces());
})();

Use client, a DataAPIClient instance, to get an AstraDBAdmin object that uses the client’s token:

AstraDBAdmin admin = client.getAdmin();

Get an AstraDBAdmin object that uses a different token than the client’s token:

AstraDBAdmin admin = client.getAdmin("APPLICATION_TOKEN");

Parameters:

Name Type Summary

token

String

If provided, this optional token is passed to the Astra DB Admin instead of the client’s token. You can use this to switch to a different permission set than that offered by the client’s token.

Returns:

AstraDBAdmin - An object used for database-level administrative tasks in Astra DB Serverless.

Example:

package com.datastax.astra.client;


import com.datastax.astra.client.admin.AstraDBAdmin;

import static com.dtsx.astra.sdk.db.domain.CloudProviderType.GCP;

public class ConnectingAdmin {
    public static void main(String[] args) {
        // Default Initialization
        DataAPIClient client = new DataAPIClient("TOKEN");

        // Accessing admin providing a new token possibly with stronger permissions
        AstraDBAdmin astradbAdmin = client.getAdmin("SUPER_USER_TOKEN");

        // Create a Database
        astradbAdmin.createDatabase("db-demo", GCP, "us-east-1").listKeyspaceNames();
    }
}

When you interact with the Data API or DevOps API directly through HTTP, you provide an application token with sufficient permissions to perform the requested operations.

When you setup Astra CLI, you provide an application token that authorizes you to run the CLI commands.

Create a database

You can create databases in the Astra Portal or programmatically.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

Use admin, an instance of the AstraDBAdmin class, to create a Serverless (Vector) database:

new_db_admin = admin.create_database(
    "DATABASE_NAME",
    cloud_provider="PROVIDER",
    region="REGION_NAME",
)

Parameters:

Name Type Summary

name

str

The desired name for the database.

wait_until_active

bool

If true (default), the method returns only after the new database is in ACTIVE state. If false, it returns immediately after issuing the creation request, and it is the responsibility of the caller to check the database status before working with it.

cloud_provider

str

One of 'aws', 'gcp' or 'azure'.

region

str

A valid cloud provider region, depending on your subscription plan and the database type.

You can use the DevOps API to Get available regions for Astra DB Serverless databases. Use the optional region-type query parameter to get supported regions for Serverless (Vector) databases only.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/regions/serverless?region-type=vector" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Accept: application/json"

keyspace

Optional[str]

Name for the database’s initial keyspace. If omitted, the DevOps API uses a default keyspace name.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the whole requested operation to complete. Note that a timeout is no guarantee that the creation request has not reached the API server.

Returns:

AstraDBDatabaseAdmin - A Database Admin object representing the newly-created database.

Example response
AstraDBDatabaseAdmin(api_endpoint="https://012...datastax.com", token="AstraCS:aAbB...")

You can’t use the database until it is created and in an ACTIVE status. By default, the command waits until the database is created and ready to use. You can set wait_until_active to false to skip waiting while the database activates. However, you can’t perform operations on the new database before it is active.

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()
new_db_admin = admin.create_database(
    "new_database",
    cloud_provider="aws",
    region="ap-south-1",
)
new_db = new_db_admin.get_database()
collection = new_db.create_collection("movies", dimension=5)
collection.insert_one({
    "title": "The Title",
    "$vector": [0.1, 0.3, -0.7, 0.9, -0.1],
})

For more information, see the Client reference.

Use admin, an instance of the AstraAdmin class, to create a Serverless (Vector) database:

const newDbAdmin = await admin.createDatabase({
  name: 'DATABASE_NAME',
  region: 'REGION_NAME',
  cloudProvider: 'PROVIDER',
});

Parameters:

Name Type Summary

config

DatabaseConfig

The properties of the database to create.

options?

AdminBlockingOptions

Options regarding the creation of the database.

Config (DatabaseConfig):

Name Type Summary

name

string

Name of the database (non-unique, human-readable identifier)

cloudProvider

DatabaseCloudProvider

A supported cloud provider: AWS, GCP, or Azure.

region

string

A valid cloud provider region, depending on your subscription plan and the database type.

You can use the DevOps API to Get available regions for Astra DB Serverless databases. Use the optional region-type query parameter to get supported regions for Serverless (Vector) databases only.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/regions/serverless?region-type=vector" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Accept: application/json"

keyspace?

string

Overrides the default name for the database’s initial keyspace.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Returns:

Promise<AstraDbAdmin> - A promised instance of the AstraDbAdmin class for that database.

You can’t use the database until it is created and in an ACTIVE status. By default, the createDatabase method blocks until the database is active. This entails polling the database status until it is ACTIVE. To disable this behavior, pass { blocking: false } to the options parameter. However, you can’t perform operations on the new database before it is active.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Obtain an admin instance
const admin = new DataAPIClient('TOKEN').admin();

(async function () {
  // Create a new database
  const dbAdmin = await admin.createDatabase({
    name: 'my-database',
    region: 'us-east1',
    cloudProvider: 'GCP',
  });

  // Get and use the database
  const db = dbAdmin.db();
  console.log(await db.listCollections());
})();

Use admin, an instance of the AstraDBAdmin class, to create a Serverless (Vector) database:

// Create a vector database with the specified name and the default options
DatabaseAdmin new_db_admin1 = admin.createDatabase(String name);

// Create a vector database with the specified name, cloud provider, and region
DatabaseAdmin new_db_admin2 = admin.createDatabase(
        String name,
        CloudProviderType cloudProvider,
        String cloudRegion);

// Create a vector database with the specified name, cloud provider, and region
// waitUntilActive determines when the method returns
DatabaseAdmin new_db_admin3 = admin.createDatabase(
        String name,
        CloudProviderType cloudProvider,
        String cloudRegion,
        boolean waitUntilActive)

Parameters:

Name Type Summary

name

String

The desired name for the database.

cloudProvider

CloudProviderType

One of 'aws', 'gcp' (default), or 'azure'.

cloudRegion

String

A valid cloud provider region, depending on your subscription plan and the database type. The default is us-east1.

You can use the DevOps API to Get available regions for Astra DB Serverless databases. Use the optional region-type query parameter to get supported regions for Serverless (Vector) databases only.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/regions/serverless?region-type=vector" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Accept: application/json"

waitUntilActive

bool

If true (default), the method returns only after the new database is in ACTIVE state. If false, it returns immediately after issuing the creation request, and it is the responsibility of the caller to check the database status before working with it.

Returns:

DatabaseAdmin - An instance of Database administration object.

You can’t use the database until it is created and in an ACTIVE status. By default, the command waits until the database is created and ready to use. You can set waitUntilActive to false to skip waiting while the database activates. However, you can’t perform operations on the new database before it is active.

Example:

package com.datastax.astra.client.admin;

import com.datastax.astra.client.DataAPIClient;
import com.dtsx.astra.sdk.db.domain.CloudProviderType;

public class CreateDatabase {
  public static void main(String[] args) {
    AstraDBAdmin astraDBAdmin = new DataAPIClient("TOKEN").getAdmin();

    // Choose a cloud provider (GCP, AZURE, AWS) and a region
    CloudProviderType cloudProvider = CloudProviderType.GCP;
    String cloudRegion = "us-east1";

    // Create a database
    DatabaseAdmin admin = astraDBAdmin.createDatabase("DATABASE_NAME", cloudProvider, cloudRegion);
  }
}

Use the DevOps API to create Serverless (Vector) and Serverless (Non-Vector) databases programmatically. However, Serverless (Non-Vector) databases aren’t compatible with the Data API, such as Collection commands and Document commands.

The application token must have sufficient permissions to perform the requested operations, such as the Organization Administrator role.

curl -sS --location -X POST "https://api.astra.datastax.com/v2/databases" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "name": "DATABASE_NAME",
  "keyspace": "",
  "cloudProvider": "CLOUD_PROVIDER",
  "region": "REGION",
  "dbType": "vector",
  "tier": "serverless",
  "capacityUnits": 1
}'

Parameters:

Name Type Summary

name

String

The desired name for the database.

keyspace

String

A name for the database’s initial keyspace.

Optional if dbType is vector. If empty, the DevOps API uses the default keyspace name of default_keyspace.

Required if dbType is omitted.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

cloudProvider

String

One of 'aws', 'gcp', or 'azure'.

region

String

A valid cloud provider region, depending on your subscription plan and the database type.

You can use the DevOps API to Get available regions for Astra DB Serverless databases. Use the optional region-type query parameter to get supported regions for Serverless (Vector) databases only.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/regions/serverless?region-type=vector" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Accept: application/json"

dbType

String

To create a Serverless (Vector) database, set this parameter to vector. To create a Serverless (Non-Vector) database, omit this parameter. If omitted, keyspace is required.

tier

String

For Astra DB Serverless databases, tier must be serverless.

capacityUnits

Integer

For Astra DB Serverless databases, capacityUnits must be 1.

Returns:

A successful request returns 201 Created and the database ID. It takes several minutes for the database to initialize and reach ACTIVE status.

For multi-region databases, use the DevOps API Add datacenters endpoint to deploy additional regions.

Create a database:

astra db create DB_NAME --region REGION --cloud CLOUD_PROVIDER \
-k KEYSPACE --if-not-exist --async

Parameters:

Name Type Summary

db_name

String

The database name.

region

String (OPTIONAL)

A valid cloud provider region, depending on your subscription plan and the database type.

You can use the DevOps API to Get available regions for Astra DB Serverless databases. Use the optional region-type query parameter to get supported regions for Serverless (Vector) databases only.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/regions/serverless?region-type=vector" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Accept: application/json"

cloud

String (OPTIONAL)

The cloud provider (gcp,azure,aws) to use for the database.

keyspace

String (OPTIONAL)

The name of the database’s initial keyspace. If omitted, the default is default_keyspace.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

--if-not-exists

flag (OPTIONAL)

If provided, this makes the operation idempotent. Check for an existing database with the same configuration.

--async

flag (OPTIONAL)

By default, the operation is synchronous and waits for the database to become active. Include this option to make the operation asynchronous.

By default, the command waits until the database is created and ready to use.

You can set --async to skip waiting while the database activates. However, you can’t perform operations on the new database before it is active.

To learn more, run astra help db create.

Find a database

Get information about one database.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

This operation is done through an instance of the AstraDBAdmin class.

db_info = admin.database_info("DB_ID")

Parameters:

Name Type Summary

id

str

The ID of the target database.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the API request.

Returns:

AdminDatabaseInfo - An object containing the requested information.

Example response

For clarity, this example is reformatted in pprint-style.

AdminDatabaseInfo(
    info=DatabaseInfo(
        id='01234567-89ab-cdef-0123-456789abcdef',
        region='us-east1',
        keyspace='default_keyspace',
        name='my_database',
        environment='prod',
        raw_info={
            'additionalKeyspaces': [
                'default_keyspace',
                'my_dreamspace'
            ],
            'capacityUnits': 1,
            'cloudProvider': 'GCP',
            'datacenters': [
                {
                    'capacityUnits': 1,
                    'cloudProvider': 'GCP',
                    'dateCreated': '2023-06-05T21:29:46Z',
                    'id': '01234567-89ab-cdef-0123-456789abcdef-1',
                    'isPrimary': True,
                    'name': 'dc-1',
                    'region': 'us-east1',
                    'regionClassification': 'standard',
                    'regionZone': 'na',
                    'secureBundleInternalUrl': 'https://...',
                    'secureBundleMigrationProxyInternalUrl': 'https://...',
                    'secureBundleMigrationProxyUrl': 'https://...',
                    'secureBundleUrl': 'https://datastax-cluster...',
                    'status': '',
                    'tier': 'serverless'
                }
            ],
            'dbType': 'vector',
            'keyspace': 'default_keyspace',
            'keyspaces': [
                'default_keyspace',
                'my_dreamspace'
            ],
            'name': 'my_database',
            'region': 'us-east1',
            'tier': 'serverless'
        }
    ),
    available_actions=[
        'getCreds',
        'addDatacenters',
        '...',
        'hibernate'
    ],
    cost={
        'costPerDayCents': 0,
        'costPerDayMRCents': 0,
        '...': 0,
        'costPerReadGbCents': 0.1,
        'costPerWrittenGbCents': 0.1
    },
    cqlsh_url='https://01234567-....datastax.com/cqlsh',
    creation_time='2023-06-05T21:29:46Z',
    data_endpoint_url='https://01234567-....datastax.com/api/rest',
    grafana_url='https://01234567-....datastax.com/d/cloud/...',
    graphql_url='https://01234567-....datastax.com/api/graphql',
    id='01234567-89ab-cdef-0123-456789abcdef',
    last_usage_time='2024-03-22T15:00:14Z',
    metrics={
        'errorsTotalCount': 0,
        'liveDataSizeBytes': 0,
        'readRequestsTotalCount': 0,
        'writeRequestsTotalCount': 0
    },
    observed_status='ACTIVE',
    org_id='aabbccdd-eeff-0011-2233-445566778899',
    owner_id='00112233-4455-6677-8899aabbddeeff',
    status='ACTIVE',
    storage={
        'displayStorage': 10,
        'nodeCount': 3,
        'replicationFactor': 1,
        'totalStorage': 5
    },
    termination_time='0001-01-01T00:00:00Z',
    raw_info={...}
)

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()

db_details = admin.database_info("01234567-...")
db_details.id
# '01234567-...'
db_details.status
# 'ACTIVE'
db_details.info.region
# 'eu-west-1'

For more information, see the Client reference.

This operation is done through an instance of the AstraAdmin class.

const dbInfo = admin.dbInfo('DB_ID');

Parameters:

Name Type Summary

id

string

The ID of the target database.

options?

WithTimeout

The options (the timeout) for this operation.

Returns:

Promise<FullDatabaseInfo> - A promise that resolves to the complete information for the corresponding database.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

const admin = new DataAPIClient('TOKEN').admin();

(async function () {
  const details = await admin.dbInfo('DB_ID');
  console.log(details.id); // '01234567-...'
  console.log(details.status); // 'ACTIVE'
  console.log(details.info.region); // 'eu-west-1'
})();
// Given 'admin', a AstraDBAdmin object
admin.getDatabaseInfo(UUID databaseId);

Parameters:

Name Type Summary

databaseId

UUID

The ID of the target database.

Returns:

DatabaseInfo - An object containing database metadata. The UUID ensures that the database is unique. Returns either one matching database or no databases.

Example:

package com.datastax.astra.client.admin;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.DatabaseInfo;

import java.util.UUID;

public class GetDatabaseInformation {
  public static void main(String[] args) {

    AstraDBAdmin astraDBAdmin = new DataAPIClient("TOKEN").getAdmin();

    // Check if a database exists
    boolean exists1 = astraDBAdmin.databaseExists("database_name");
    boolean exists2 = astraDBAdmin.databaseExists(UUID.fromString("<database_id>"));

    // Find a database by name (names may not be unique)
    DatabaseInfo databaseInformation = astraDBAdmin
            .getDatabaseInfo(UUID.fromString("<database_id>"));
    System.out.println("Name=" + databaseInformation.getName());
  }
}

Use the DevOps API to get information about a database programmatically.

The application token must have sufficient permissions to perform the requested operations, such as the Database Administrator role.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/databases/DB_ID" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Returns:

A successful request returns 200 Created and an object containing database information.

Example response

This example response is truncated for brevity.

{
  "id": "DB_ID",
  "orgId": "organizations/ORG_ID",
  "ownerId": "users/USER_ID",
  "info": {
    "name": "DB_NAME",
    "keyspace": "INITIAL_KEYSPACE_NAME",
    "cloudProvider": "CLOUD_PROVIDER",
    "region": "REGION",
    "additionalKeyspaces": [
      "SECOND_KEYSPACE_NAME"
    ],
    "dbType": "vector"
  },
  "creationTime": "2012-11-01T22:08:41+00:00",
  "terminationTime": "2019-11-01T22:08:41+00:00",
  "status": "ACTIVE",
  # Response truncated for brevity
}

Get database metadata by database name:

astra db describe DB_NAME

Get database metadata by database ID:

astra db describe DB_ID

Parameters:

Name Type Summary

database_name

String

The desired name for the database (does not ensure uniqueness)

database_id

String

The ID of the target database.

Example response
+------------------+-----------------------------------------+
| Attribute        | Value                                   |
+------------------+-----------------------------------------+
| Name             | astra_db_client                         |
| id               | 4391daae-016c-49e3-8d0a-b4633a86082c    |
| Cloud            | GCP                                     |
| Regions          | us-east1                                |
| Status           | ACTIVE                                  |
| Vector           | Enabled                                 |
| Default Keyspace | default_keyspace                        |
| Creation Time    | 2024-02-24T01:20:03Z                    |
|                  |                                         |
| Keyspaces        | [0] default_keyspace                    |
|                  |                                         |
|                  |                                         |
| Regions          | [0] us-east1                            |
|                  |                                         |
+------------------+-----------------------------------------+

Find all databases

Retrieve the listing of all databases.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

This operation is done through an instance of the AstraDBAdmin class.

all_databases = admin.list_databases()

Parameters:

Name Type Summary

max_time_ms

Optional[int]

A timeout, in milliseconds, for the API request.

Returns:

CommandCursor[AdminDatabaseInfo] - An iterable of AdminDatabaseInfo objects, each carrying detailed information on a database.

Example response

This example is abridged and reformated in pprint-style for clarity. It shows a single AdminDatabaseInfo from the cursor.

[
    # Preceding content truncated
    AdminDatabaseInfo(
        info=DatabaseInfo(
            id='01234567-89ab-cdef-0123-456789abcdef',
            region='us-east1',
            keyspace='default_keyspace',
            name='my_database',
            environment='prod',
            raw_info={
                'additionalKeyspaces': [
                    'default_keyspace',
                    'my_dreamspace'
                ],
                'capacityUnits': 1,
                'cloudProvider': 'GCP',
                'datacenters': [
                    {
                        'capacityUnits': 1,
                        'cloudProvider': 'GCP',
                        'dateCreated': '2023-06-05T21:29:46Z',
                        'id': '01234567-89ab-cdef-0123-456789abcdef-1',
                        'isPrimary': True,
                        'name': 'dc-1',
                        'region': 'us-east1',
                        'regionClassification': 'standard',
                        'regionZone': 'na',
                        'secureBundleInternalUrl': 'https://...',
                        'secureBundleMigrationProxyInternalUrl': 'https://...',
                        'secureBundleMigrationProxyUrl': 'https://...',
                        'secureBundleUrl': 'https://datastax-cluster...',
                        'status': '',
                        'tier': 'serverless'
                    }
                ],
                'dbType': 'vector',
                'keyspace': 'default_keyspace',
                'keyspaces': [
                    'default_keyspace',
                    'my_dreamspace'
                ],
                'name': 'my_database',
                'region': 'us-east1',
                'tier': 'serverless'
            }
        ),
        available_actions=[
            'getCreds',
            'addDatacenters',
            '...',
            'hibernate'
        ],
        cost={
            'costPerDayCents': 0,
            'costPerDayMRCents': 0,
            '...': 0,
            'costPerReadGbCents': 0.1,
            'costPerWrittenGbCents': 0.1
        },
        cqlsh_url='https://01234567-....datastax.com/cqlsh',
        creation_time='2023-06-05T21:29:46Z',
        data_endpoint_url='https://01234567-....datastax.com/api/rest',
        grafana_url='https://01234567-....datastax.com/d/cloud/...',
        graphql_url='https://01234567-....datastax.com/api/graphql',
        id='01234567-89ab-cdef-0123-456789abcdef',
        last_usage_time='2024-03-22T15:00:14Z',
        metrics={
            'errorsTotalCount': 0,
            'liveDataSizeBytes': 0,
            'readRequestsTotalCount': 0,
            'writeRequestsTotalCount': 0
        },
        observed_status='ACTIVE',
        org_id='aabbccdd-eeff-0011-2233-445566778899',
        owner_id='00112233-4455-6677-8899aabbddeeff',
        status='ACTIVE',
        storage={
            'displayStorage': 10,
            'nodeCount': 3,
            'replicationFactor': 1,
            'totalStorage': 5
        },
        termination_time='0001-01-01T00:00:00Z',
        raw_info={...}
    ),
    # Subsequent content truncated
]

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()

database_cursor = admin.list_databases()
database_list = list(database_cursor)
len(database_list)
# 3
database_list[2].id
# '01234567-...'
database_list[2].status
# 'ACTIVE'
database_list[2].info.region
# 'eu-west-1'

For more information, see the Client reference.

This operation is done through an instance of the AstraAdmin class.

const dbs = await admin.listDatabases();

Parameters:

Name Type Summary

options

ListDatabasesOptions

The filters to use when listing the database

Name Type Summary

include?

DatabaseStatus

Allows filtering by database status. Defaults to NONTERMINATED.

provider?

DatabaseCloudProviderFilter

Allows filtering by cloud provider. Defaults to ALL.

limit?

number

Number of databases to return, between 1-100. Defaults to 25.

skip?

number

Number of databases to skip. Defaults to 0.

maxTimeMs?

number

The maximum time in milliseconds that the client should wait for the operation to complete.

Returns:

Promise<FullDatabaseInfo[]> - A promised list of the complete information for all the databases matching the given filter.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

const admin = new DataAPIClient('TOKEN').admin();

(async function () {
  const activeDbs = await admin.listDatabases({ include: 'ACTIVE' });

  for (const db of activeDbs) {
    console.log(`Database ${db.name} is active`);
  }
})();

The list databases function is available in the AstraDBAdmin class.

// Given 'admin' a AstraDBAdmin object
List<DatabaseInfo> infoList = admin.listDatabases();

Parameters:

None.

Returns:

List<DatabaseInfo> - List of database metadata exposed as a stream.

Example:

package com.datastax.astra.client.admin;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.DatabaseInfo;

public class ListDatabases {
    public static void main(String[] args) {
        
        // Initialization of admin (astra only)
        AstraDBAdmin astraDBAdmin = new DataAPIClient("TOKEN").getAdmin();

        // Display all database information
        astraDBAdmin.listDatabases().stream()
                .map(DatabaseInfo::getId)
                .forEach(System.out::println);

        // Display all database names
        astraDBAdmin.listDatabaseNames();
    }
}

Use the DevOps API to get information about all databases in an organization.

The application token must have sufficient permissions to perform the requested operations, such as the Organization Administrator role. Additionally, the application token identifies the organization to query.

curl -sS --location -X GET "https://api.astra.datastax.com/v2/databases" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Returns:

A successful request returns 200 Created and an array of objects containing information about each database in the organization.

Example response

This example response contains one database object, and it is truncated for brevity.

[
  {
    "id": "DB_ID",
    "orgId": "organizations/ORG_ID",
    "ownerId": "users/USER_ID",
    "info": {
      "name": "DB_NAME",
      "keyspace": "INITIAL_KEYSPACE_NAME",
      "cloudProvider": "CLOUD_PROVIDER",
      "region": "REGION",
      "additionalKeyspaces": [
        "SECOND_KEYSPACE_NAME"
      ],
      "dbType": "vector"
    },
    "creationTime": "2012-11-01T22:08:41+00:00",
    "terminationTime": "2019-11-01T22:08:41+00:00",
    "status": "ACTIVE",
    # Response truncated for brevity
  }
]

List all of your databases:

astra db list
Example response
+---------------------+--------------+-----------+-------+---+-----------+
| Name                | id           | Regions   | Cloud | V | Status    |
+---------------------+--------------+-----------+-------+---+-----------+
| astra_db_client     | *DB_ID*      | us-east1  | gcp   | ■ | ACTIVE    |
+---------------------+--------------+-----------+-------+---+-----------+

Drop a database

Terminating a database permanently deletes all of its data, including automatic backups. You can’t undo this action.

Delete a database and erase all data stored in it.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

The database deletion is done through an instance of the AstraDBAdmin class.

admin.drop_database("DB_ID")

Parameters:

Name Type Summary

id

str

The ID of the target database.

wait_until_active

bool

If true (default), the method returns only after the database is actually been deleted. If false, it returns immediately after issuing the drop request, and it is the responsibility of the caller to check the database status/availability after that, if desired.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the whole requested operation to complete. Note that a timeout is no guarantee that the deletion request has not reached the API server.

Returns:

Dict - A dictionary in the form {"ok": 1} if the method succeeds.

Example response
{"ok": 1}

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()

database_list_pre = list(admin.list_databases())
len(database_list_pre)
# 3
admin.drop_database("01234567-...")
# {'ok': 1}
database_list_post = list(admin.list_databases())
len(database_list_post)
# 2

View this topic in more detail on the Client reference.

The database termination is done through an instance of the AstraAdmin class.

await admin.dropDatabase('DB_ID');

Parameters:

Name Type Summary

db

Db | string

The ID of the target database.

options?

AdminBlockingOptions

Options regarding the termination of the database.

By default, the dropDatabase method blocks until the database is deleted. This entails polling the database status until it is TERMINATED. To disable this behavior, pass { blocking: false } to the options parameter.

Returns:

Promise<void> - A promise that resolves when the database is terminated.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

const admin = new DataAPIClient('TOKEN').admin();

(async function () {
  await admin.dropDatabase('DB_ID');
})();

The delete database function is available in the AstraDBAdmin class.

// Given 'admin', a AstraDBAdmin object
// Delete an existing database by name
admin.dropDatabase(String name);

// Delete an existing database by ID
admin.dropDatabase(UUID id);

Parameters:

Name Type Summary

id

UUID

The identifier of the database to delete.

name

String

The name of the database to delete.

Returns:

boolean - Flag indicating if the database was deleted.

Example:

package com.datastax.astra.client.admin;

import com.datastax.astra.client.DataAPIClient;

import java.util.UUID;

public class DropDatabase {
  public static void main(String[] args) {
    AstraDBAdmin astraDBAdmin = new DataAPIClient("TOKEN").getAdmin();

    // Delete an existing database
    astraDBAdmin.dropDatabase("<database_name>");

    // Delete an existing database by ID
    astraDBAdmin.dropDatabase(UUID.fromString("<database_id>"));

  }
}

Use the DevOps API to delete a database. This operation is a POST request with no body.

The application token must have sufficient permissions to perform the requested operations, such as the Organization Administrator role.

curl -sS --location -X POST "https://api.astra.datastax.com/v2/databases/DB_ID/terminate" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Returns:

A successful request returns 202 Accepted and initiates the termination process. The database isn’t instantly deleted, and the termination process can take some time. To monitor the termination process, you can check the database status in the Astra Portal.

Delete a database by ID:

astra db delete DB_ID

Delete a database by name:

astra db delete DB_NAME

Parameters:

Name Type Summary

db_id

UUID

The ID of the database to delete

db_name

String

The name of the database to delete.

Get a Database Admin

The Database Admin object can perform administrative tasks within a database, such as managing keyspaces.

The object name varies by client language:

  • For Python, it is AstraDBDatabaseAdmin.

  • For TypeScript, it is AstraDbAdmin.

  • For Java, it is DatabaseAdmin.

An Astra DB Admin can instantiate one Database Admin object for an existing database.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

Get an AstraDBDatabaseAdmin from an AstraDBAdmin:

db_admin = admin.get_database_admin("DB_ID")
Get DatabaseAdmin from Database

As an alternative to the previous method, you can use the get_database_admin method to get a DatabaseAdmin from a Database object:

db_admin = database.get_database_admin()

DataStax typically recommends the get_database_admin method when using the Data API with Hyper-Converged Database, which has no notion of an AstraDBAdmin.

Parameters:

Name Type Summary

id

str

The ID of the target database.

Returns:

AstraDBDatabaseAdmin - A Database Admin object representing the target database.

Example response

The following example is truncated for clarity:

AstraDBDatabaseAdmin(api_endpoint="https://012...datastax.com", token="AstraCS:aAbB...")

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
admin = client.get_admin()

db_admin = admin.get_database_admin("01234567-...")
db_admin.list_keyspaces()
# ['default_keyspace']
db_admin.create_keyspace("that_other_one")
# {'ok': 1}
db_admin.list_keyspaces()
# ['default_keyspace', 'that_other_one']

For more information, see the Client reference.

Get a dbAdmin by database endpoint:

const dbAdmin = admin.dbAdmin('ENDPOINT');

Use the convenience method to get a dbAdmin by database ID and region:

const dbAdmin = admin.dbAdmin('DB_ID', 'REGION');
Get AstraDbAdmin from Db

As an alternative to the previous method, you can use the admin method to get an AstraDbAdmin from a Db object:

const dbAdmin = db.admin({ environment: DB_ENVIRONMENT });

(async function () {
  await dbAdmin.createKeyspace(KEYSPACE_NAME);
  console.log(await dbAdmin.listKeyspaces());
})();

DataStax typically recommends the admin method when using the Data API with Hyper-Converged Database, which has no notion of an AstraAdmin.

Parameters:

Name Type Summary

endpoint

string

The database’s API endpoint, typically formatted as \https://DB_ID-REGION.apps.astra.datastax.com.

dbOptions?

DbSpawnOptions

The options to use for the underlying database (see Connect to a Database for more information). The admin options are taken from the parent admin instance.

Returns:

AstraDbAdmin - An object used for database-specific-level administrative tasks.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Spawn an AstraDbAdmin instance
const admin = new DataAPIClient('TOKEN').admin();
const dbAdmin = admin.dbAdmin('ENDPOINT');

(async function () {
  // ['default_keyspace']
  console.log(await dbAdmin.listKeyspaces());

  await dbAdmin.createKeyspace('that_other_one');

  // ['default_keyspace', 'that_other_one']
  console.log(await dbAdmin.listKeyspaces());
})();

For more information, see the Java client administrative classes reference.

Get a DatabaseAdmin from with an AstraDBAdmin and database ID:

// Given 'admin', a AstraDBAdmin object
DatabaseAdmin dbAdmin = admin
  .getDatabaseAdmin(UUID.fromString("databaseId"));
Get DatabaseAdmin from Database

As an alternative to the previous method, you can use the getDatabaseAdmin method to get a DatabaseAdmin from a Database object:

DataAPIDatabaseAdmin client
    .getDatabase(dataApiUrl)
    .getDatabaseAdmin();

DataStax typically recommends the getDatabaseAdmin method when using the Data API with Hyper-Converged Database, which has no notion of an AstraDBAdmin.

Parameters:

Name Type Summary

databaseId

UUID

The ID of the target database for which to create a Database Admin object.

Returns:

DatabaseAdmin - An instance of a Database administration object.

Example:

package com.datastax.astra.client.database_admin;


import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.admin.AstraDBAdmin;
import com.datastax.astra.client.admin.DatabaseAdmin;

import java.util.UUID;

public class GetDatabaseAdmin {
    public static void main(String[] args) {
        // Default Initialization
        DataAPIClient client = new DataAPIClient("TOKEN");

        // Accessing admin providing a new token possibly with stronger permissions
        AstraDBAdmin astradbAdmin = client.getAdmin("SUPER_USER_TOKEN");

        DatabaseAdmin admin = astradbAdmin.getDatabaseAdmin(UUID.fromString("<database_id>"));
    }
}

When you interact with the Data API or DevOps API directly through HTTP, you provide an application token with sufficient permissions to perform the requested operations.

When you setup Astra CLI, you provide an application token that authorizes you to run the CLI commands.

Create a keyspace

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Serverless (Vector) databases have an initial keyspace named default_keyspace. You can override the initial keyspace name when you create the database, if desired.

You can create more keyspaces as needed, such as for better application structure.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

db_admin.create_keyspace("KEYSPACE_NAME")

Parameters:

Name Type Summary

name

str

The keyspace name. If supplying a keyspace that exists already, the method call proceeds as usual, no errors are raised, and the whole invocation is a no-op.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

wait_until_active

bool

If True (default), the method returns only after the target database is in ACTIVE state again (a few seconds, usually). If False, it will return right after issuing the creation request to the DevOps API, and it will be responsibility of the caller to check the database status/keyspace availability before working with it.

update_db_keyspace

bool

Use this parameter to create a keyspace and immediately start using it. If True, the new keyspace becomes the working keyspace for the Database or AsyncDatabase object. For example, the following code creates a keyspace, and then modifies the database instance to work in the "new_keyspace":

database = ...
database.get_database_admin(...).create_keyspace(
    "new_keyspace",
    update_db_keyspace=True,
)

max_time_ms

Optional[int]

A timeout, in milliseconds, for the whole requested operation to complete. Note that a timeout is no guarantee that the creation request has not reached the API server.

Returns:

Dict - A dictionary of the form {"ok": 1} if the operation succeeds. Otherwise, an exception is raised.

Example response
{"ok": 1}

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
db_admin = client.get_admin().get_database_admin("01234567-...")

db_admin.list_keyspaces()
# ['default_keyspace']
db_admin.create_keyspace("that_other_one")
# {'ok': 1}
db_admin.list_keyspaces()
# ['default_keyspace', 'that_other_one']

For more information, see the Client reference.

await dbAdmin.createKeyspace('KEYSPACE_NAME');

Parameters:

Name Type Summary

name

string

The name of the keyspace to create.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

options?

CreateKeyspaceOptions

Options regarding the creation of the keyspace.

Use updateDbKeyspace to create a keyspace and immediately start using it. If true, the new keyspace becomes the working keyspace for the Db object. For example, the following code creates a keyspace and modifies the db instance to work in the 'new_keyspace':

const db = client.db('ENDPOINT');

console.log(db.keyspace);

await db.admin().createKeyspace('new_keyspace', {
  updateDbKeyspace: true,
});

console.log(db.keyspace);

Returns:

Promise<void> - A promise that resolves when the keyspace is created (or when the initial request completes if not blocking).

The createKeyspace method blocks until the database is active, by default. This entails polling the database status until it is ACTIVE. You can disable this behavior by passing { blocking: false } to the options parameter.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Spawn an AstraDbAdmin instance
const admin = new DataAPIClient('TOKEN').admin();
const dbAdmin = admin.dbAdmin('ENDPOINT');

(async function () {
  // ['default_keyspace']
  console.log(await dbAdmin.listKeyspaces());

  await dbAdmin.createKeyspace('that_other_one');

  // ['default_keyspace', 'that_other_one']
  console.log(await dbAdmin.listKeyspaces());
})();
// Given 'dbAdmin', a DatabaseAdmin object
void dbAdmin.createKeyspace("new_keyspace");

// Given 'dbAdmin', also change the associated `database` object
void dbAdmin.createKeyspace("new_keyspace", true);

Parameters:

Name Type Summary

keyspace

String

The unique name for the keyspace

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

updateDbKeyspace (optional)

boolean

Use this parameter to create a keyspace and immediately start using it. If True, the new keyspace becomes the working keyspace for the Database object. For example, the following pattern creates a keyspace, and then modifies the db object to work in the "new_keyspace":

db
  .getDatabaseAdmin()
  .createKeyspace("new_keyspace", true);

Returns:

None.

Example:

package com.datastax.astra.client.database_admin;

import com.datastax.astra.client.Database;

public class CreateKeyspace {
  public static void main(String[] args) {
    // Default initialization
    Database db = new Database("API_ENDPOINT", "TOKEN");

    // Create a new keyspace
    db.getDatabaseAdmin().createKeyspace("<keyspace_name>");

    // The database can be mutate on keyspace creation
    db.getDatabaseAdmin().createKeyspace("<keyspace2_name>", true);
  }
}

Use the DevOps API to create keyspaces programmatically. This operation is a POST request that includes the new keyspace name as a path parameter.

The application token must have sufficient permissions to perform the requested operations, such as the Organization Administrator role.

curl -sS --location -X POST "https://api.astra.datastax.com/v2/databases/DB_ID/keyspaces/KEYSPACE_NAME" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Returns:

A successful request returns 201 Created.

Create a keyspace in a database:

astra db create-keyspace DB_NAME -k KEYSPACE_NAME

Parameters:

Name Type Summary

db_name

String

The name of the database where you want to create the keyspace. The database must already exist.

keyspace_name

String

The unique name for the keyspace.

List keyspaces

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Get a list of the keyspaces in a database.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

keyspaces = db_admin.list_keyspaces()

Parameters:

Name Type Summary

max_time_ms

Optional[int]

A timeout, in milliseconds, for the API request.

Returns:

List[str] - A list of the keyspaces with their names appearing in no particular order.

Example response
['default_keyspace', 'that_other_one']

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
db_admin = client.get_admin().get_database_admin("01234567-...")

db_admin.list_keyspaces()
# ['default_keyspace']
db_admin.create_keyspace("that_other_one")
# {'ok': 1}
db_admin.list_keyspaces()
# ['default_keyspace', 'that_other_one']

For more information, see the Client reference.

const keyspaces = await dbAdmin.listKeyspaces();

Parameters:

Name Type Summary

options?

WithTimeout

Options regarding the timeout for the operation.

Returns:

Promise<string[]> - A list of the keyspaces, with the first keyspace being the default one.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Spawn an AstraDbAdmin instance
const admin = new DataAPIClient('TOKEN').admin();
const dbAdmin = admin.dbAdmin('ENDPOINT');

(async function () {
  // ['default_keyspace']
  console.log(await dbAdmin.listKeyspaces());

  await dbAdmin.createKeyspace('that_other_one');

  // ['default_keyspace', 'that_other_one']
  console.log(await dbAdmin.listKeyspaces());
})();
// Given 'dbAdmin', a DatabaseAdmin object
Set<String> names = dbAdmin.listKeyspaceNames();

Parameters:

None.

Returns:

keyspace - A Set<String> containing the list of available keyspaces in current database.

Example:

package com.datastax.astra.client.database_admin;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.admin.AstraDBAdmin;
import com.datastax.astra.client.admin.DatabaseAdmin;

import java.util.Set;
import java.util.UUID;

public class ListKeyspaces {
    public static void main(String[] args) {

        DataAPIClient client = new DataAPIClient("TOKEN");

        // Accessing admin providing a new token possibly with stronger permissions
        AstraDBAdmin admin = client.getAdmin("SUPER_USER_TOKEN");

        DatabaseAdmin dbAdmin = admin.getDatabaseAdmin(UUID.fromString("DATABASE_ID"));

        // List available keyspaces
        Set<String> names = dbAdmin.listKeyspaceNames();
    }
}

Use Find a database to get a list of keyspaces within a database.

List keyspaces in a database:

astra db list-keyspaces DB_NAME

Parameters:

Name Type Summary

db_name

String

The name of the database from which to get the keyspaces.

Result
+----------------------------+
| Name                       |
+----------------------------+
| default_keyspace (default) |
| keyspace2                 |
+----------------------------+

Drop a keyspace

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Delete a keyspace in a database and erase all data stored in that keyspace.

Programmatically, it is possible to delete all keyspaces in a database, but DataStax doesn’t recommend this.

  • Python

  • TypeScript

  • Java

  • curl

  • CLI

For more information, see the Client reference.

db_admin.drop_keyspace("KEYSPACE_NAME")

Parameters:

Name Type Summary

name

str

The keyspace to delete. If it does not exist in this database, an error is raised.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

wait_until_active

bool

If True (default), the method returns only after the target database is in ACTIVE state again (a few seconds, usually). If False, it will return right after issuing the deletion request to the DevOps API, and it will be responsibility of the caller to check the database status/keyspace availability before working with it.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the whole requested operation to complete. Note that a timeout is no guarantee that the deletion request has not reached the API server.

Returns:

Dict - A dictionary in the form of {"ok": 1}, if the operation succeeds. Otherwise, an exception is raised.

Example response
{"ok": 1}

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
db_admin = client.get_admin().get_database_admin("01234567-...")

db_admin.list_keyspaces()
# ['default_keyspace', 'that_other_one']
db_admin.drop_keyspace("that_other_one")
# {'ok': 1}
db_admin.list_keyspaces()
# ['default_keyspace']

For more information, see the Client reference.

await dbAdmin.dropKeyspace('KEYSPACE_NAME');

Parameters:

Name Type Summary

name

string

The name of the keyspace to drop.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

options?

AdminBlockingOptions

Blocking options regarding the deletion of the keyspace.

Returns:

Promise<void> - A promise that resolves when the keyspace is deleted (or when the initial request completes if not blocking).

The dropKeyspace method blocks until the database is active, by default. This entails polling the database status until it is ACTIVE. You can disable this behavior by passing { blocking: false } to the options parameter.

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Spawn an AstraDbAdmin instance
const admin = new DataAPIClient('TOKEN').admin();
const dbAdmin = admin.dbAdmin('ENDPOINT');

(async function () {
  // ['default_keyspace', 'that_other_one']
  console.log(await dbAdmin.listKeyspaces());

  await dbAdmin.dropKeyspace('that_other_one');

  // ['default_keyspace']
  console.log(await dbAdmin.listKeyspaces());
})();
// Given 'dbAdmin', a DatabaseAdmin object
void dbAdmin.dropKeyspace("KEYSPACE_NAME");

Parameters:

Name Type Summary

keyspace

String

The name of the keyspace to delete.

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Example:

package com.datastax.astra.client.database_admin;

import com.datastax.astra.client.Database;

public class DropKeyspace {

    public static void main(String[] args) {
        // Default initialization
        Database db = new Database("API_ENDPOINT", "TOKEN");

        // Drop a Namespace
        db.getDatabaseAdmin().dropKeyspace("<keyspace_name>");
    }
}

Use the DevOps API to delete keyspaces programmatically. This operation is a DELETE request that includes the target keyspace as a path parameter.

The application token must have sufficient permissions to perform the requested operations, such as the Organization Administrator role.

curl -sS -location -X DELETE "https://api.astra.datastax.com/v2/databases/DB_ID/keyspaces/KEYSPACE_NAME" \
--header "Authorization: Bearer APPLICATION_TOKEN" \
--header "Content-Type: application/json"

Astra DB APIs use the term keyspace to refer to both namespaces and keyspaces.

Returns:

A successful request returns 204 No Content.

Delete a keyspace:

astra db delete-keyspace DB_NAME -k KEYSPACE_NAME

Parameters:

Name Type Summary

db_name

String

The name of the database containing the keyspace to delete.

keyspace_name

String

The name of the keyspace to delete.

Find embedding providers

Get information about embedding providers for Astra DB vectorize, including supported providers, models, dimensions, and other configuration parameters.

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the Client reference.

embedding_providers = db_admin.find_embedding_providers()

Parameters:

Name Type Summary

max_time_ms

Optional[int]

A timeout, in milliseconds, for the command to complete.

Returns:

FindEmbeddingProvidersResult - An object representing the full response from the findEmbeddingProviders Data API command.

The information in the response is arranged as a hierarchy of nested classes, structured like the Data API JSON response. Refer to the following examples or consult the involved classes in the client reference:

Example response
# providers list abridged for clarity:
FindEmbeddingProvidersResult(embedding_providers=azureOpenAI, bedrock, huggingface, ...)

You can use filters to navigate the response. The actual response depends on the models available for a given database.

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
db_admin = client.get_admin().get_database_admin("01234567-...")


>>> find_e_p_result = db_admin.find_embedding_providers()
>>> find_e_p_result  # output shortened and reformatted for clarity:
FindEmbeddingProvidersResult(
    embedding_providers=..., huggingface, ..., mistral, openai, ...
)

# output shortened for clarity:
>>> find_e_p_result.embedding_providers.keys()
dict_keys(['openai', ..., 'huggingface', 'mistral'])

# output reformatted for clarity:
>>> find_e_p_result.embedding_providers['openai']
EmbeddingProvider(
    display_name='OpenAI',
    models=[
        EmbeddingProviderModel(name='text-embedding-3-small'),
        EmbeddingProviderModel(name='text-embedding-3-large'),
        EmbeddingProviderModel(name='text-embedding-ada-002')
    ]
)

>>> find_e_p_result.embedding_providers['openai'].display_name
'OpenAI'

# output reformatted for clarity:
>>> find_e_p_result.embedding_providers['openai'].parameters
[
    EmbeddingProviderParameter(name='organizationId'),
    EmbeddingProviderParameter(name='projectId')
]

# output reformatted for clarity:
>>> find_e_p_result.embedding_providers['openai'].supported_authentication
{
    'HEADER': EmbeddingProviderAuthentication(
        enabled=True, tokens=EmbeddingProviderToken('x-embedding-api-key')
    ),
    'SHARED_SECRET': EmbeddingProviderAuthentication(
        enabled=True, tokens=EmbeddingProviderToken('providerKey')
    ),
    'NONE': EmbeddingProviderAuthentication(enabled=False, tokens=)
}

>>> my_model = find_e_p_result.embedding_providers['openai'].models[1]
>>> my_model
EmbeddingProviderModel(name='text-embedding-3-large')

>>> my_model.parameters
[EmbeddingProviderParameter(name='vectorDimension')]

>>> my_model.parameters[0].parameter_type
'number'

>>> my_model.parameters[0].validation
{'numericRange': [256, 3072]}

>>> my_model.parameters[0].default_value
'3072'

For more information, see the Client reference.

const embeddingProviders = await dbAdmin.findEmbeddingProviders();

Parameters:

Name Type Summary

options?

WithTimeout

The options (the timeout) for this operation.

Returns:

Promise<FindEmbeddingProvidersResult[]> - An object representing the full response from the findEmbeddingProviders API command.

The information in the response is arranged as a hierarchy of nested classes, structured like the Data API JSON response. Refer to the following examples or consult the involved classes in the client reference:

Example:

import { DataAPIClient } from '@datastax/astra-db-ts'

// Spawn an AstraDbAdmin instance
const admin = new DataAPIClient('TOKEN').admin();
const dbAdmin = admin.dbAdmin('ENDPOINT');

(async function () {
  const info = await dbAdmin.findEmbeddingProviders();

  // { openai: { ... }, huggingface: { ... }, mistral: { ... }, ... }
  console.log(info);

  // ['openai', 'huggingface', 'mistral', ...]
  console.log(Object.keys(info))

  // { displayName: 'OpenAI', parameters: [...], models: [...], ... }
  console.log(info.openai);

  // 'OpenAI'
  console.log(info.openai.displayName);

  // [{ name: 'organizationId', ... }, { name: 'projectId', ... }]
  console.log(info.openai.parameters);

  // { HEADER: { enabled: true, ... }, SHARED_SECRET: { enabled: true, ... }, NONE: { enabled: false, ... } }
  console.log(info.openai.supportedAuthentication);

  // { name: 'text-embedding-3-small', vectorDimension: null, parameters: { ... } }
  console.log(info.openai.models[0]);

  // [{ name: 'vectorDimension', ... }]
  console.log(info.openai.models[0].parameters);

  // 'number'
  console.log(info.openai.models[0].parameters[0].type);

  // { numericRange: [256, 3072] }
  console.log(info.openai.models[0].parameters[0].validation);

  // '3072'
  console.log(info.openai.models[0].parameters[0].defaultValue);
})();

For more information, see the Client reference.

// Given 'dbAdmin', a DatabaseAdmin object
FindEmbeddingProvidersResult embeddingProviders =
      dbAdmin.findEmbeddingProviders();

Parameters:

None.

Returns:

FindEmbeddingProvidersResult - An object representing the full response from the findEmbeddingProviders API command.

The information in the response is arranged as a hierarchy of nested classes, structured like the API JSON response itself. It wraps a map with provider names as keys and EmbeddingProvider objects as values.

Example response
Provider: openai

+ Authentication Header
  + Token accepted=x-embedding-api-key, forwarded=Authorization
+ Models:
  + Name=text-embedding-3-small
  + Name=text-embedding-3-large
  + Name=text-embedding-ada-002, dimension=1536

Example:

package com.datastax.astra.client.database_admin;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.Database;
import com.datastax.astra.client.admin.DatabaseAdmin;
import com.datastax.astra.client.model.EmbeddingProvider;
import com.datastax.astra.client.model.FindEmbeddingProvidersResult;

import java.util.Map;

public class FindEmbeddingProviders {
    public static void main(String[] args) {
        Database db = new Database("API_ENDPOINT","TOKEN");
        DatabaseAdmin dbAdmin = db.getDatabaseAdmin();

        // was actually a new object not the initial
        // RATIONAL: as you can come from AstraDBAdmin potentially you not always have a database object created
        Database db1 = dbAdmin.getDatabase();
        Database db2 = dbAdmin.getDatabase("keyspace2");


        FindEmbeddingProvidersResult fepr = db.getDatabaseAdmin().findEmbeddingProviders();

        Map<String, EmbeddingProvider> providers = fepr.getEmbeddingProviders();
        for (Map.Entry<String, EmbeddingProvider> entry : providers.entrySet()) {
            System.out.println("\nProvider: " + entry.getKey());
            EmbeddingProvider provider = entry.getValue();
            provider.getHeaderAuthentication().ifPresent(headerAuthentication -> {
                System.out.println("+ Authentication Header");
                headerAuthentication.getTokens().forEach(token -> {
                    System.out.println("  +"
                            + " Token accepted=" + token.getAccepted()
                            + ", forwarded=" + token.getForwarded());
                });
            });
            System.out.println("+ Models:");
            for(EmbeddingProvider.Model model : provider.getModels()) {
                System.out.println("  + Name=" +
                        model.getName() + ((model.getVectorDimension() != null) ? ", dimension=" + model.getVectorDimension() : ""));
            }
        }
    }
}

Use the findEmbeddingProviders Data API command to get information about embedding providers for vectorize. Don’t include a keyspace in the request URL.

The application token must have sufficient permissions to perform the requested operations, such as the Database Administrator role.

curl -sS -location -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findEmbeddingProviders": {}
}'

You can use | jq to filter the response:

curl -sS --location -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findEmbeddingProviders": {}
}' | jq .status.embeddingProviders.MODEL_NAME

Returns:

A successful response returns a JSON object describing the embedding providers and settings available for the specified database.

Example response

This example response is shortened and edited for clarity.

{
  "status": {
    "embeddingProviders": {
      "openai": {
        "displayName": "OpenAI",
        "url": "https://api.openai.com/v1/",
        "supportedAuthentication": {
          "SHARED_SECRET": {
            "enabled": true,
            "tokens": [
              {
                "accepted": "providerKey",
                "forwarded": "Authorization"
              }
            ]
          },
          # Truncated
        },
        "parameters": [
          {
            "name": "organizationId",
            "type": "STRING",
            "required": false,
            "defaultValue": "",
            "validation": {},
            "help": "Optional, OpenAI Organization ID. If provided [...]",
            "displayName": "Organization ID",
            "hint": "Add an (optional) organization ID"
          },
          # Truncated
        ],
        "models": [
          {
            "name": "text-embedding-3-small",
            "vectorDimension": null,
            "parameters": [
              {
                "name": "vectorDimension",
                "type": "number",
                "required": true,
                "defaultValue": "1536",
                "validation": {
                  "numericRange": [
                    2,
                    1536
                  ]
                },
                "help": "Vector dimension to use in [...]"
              }
            ]
          },
          # Truncated
        ]
      },
      # Truncated
    }
  }
}

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com