Collections reference

Collections store documents in keyspaces.

Use the Database class to manage collections, and the Collection class to work with the data in collections.

You can create up to ten collections in each database.

Collections use Storage-Attached Indexes (SAIs) to enable efficient queries on indexed properties. SAI indexes are created automatically when you insert documents into a collection. The default number of SAI indexes allowed per database is 100.

You can configure the number of collections per database using a setting in the cassandra.yaml file. You can configure the number of SAI indexes per database by setting a value in a .env file.

How to configure number of collections and SAIs
  1. Open the cassandra.yaml file.

  2. Find the sai_indexes_total_failure_threshold setting and change to the desired number of SAI indexes.

  3. Save the file.

  4. Open the .env file.

  5. Find the MAX_COLLECTIONS setting and change to the desired number of collections. 5a. Add the following lines with your desired values: int DEFAULT_MAX_COLLECTIONS = 10; int DEFAULT_INDEXES_AVAILABLE_PER_DATABASE = 100;

  6. Save the file.

  7. Restart the database.

Prerequisites

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

Create a collection

Create a new collection in a keyspace.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

collection = database.create_collection(
  "DB_COLLECTION",
  namespace="DB_NAMESPACE"),
  check_exists=False)

Create a new collection to store vector data.

collection = database.create_collection(
    "vector_test3",
    dimension=5,
    metric=VectorMetric.COSINE,  # or simply "cosine"
    keyspace=DB_KEYSPACE,
    check_exists=False,
)
print(f"* Collection: {collection.full_name}\n")

Create a new collection that generates vector embeddings automatically.

collection = database.create_collection(
    "vector_test3",
    dimension=5,
    metric=VectorMetric.COSINE,  # or simply "cosine"
    service={"provider": OPEN_AI_PROVIDER, "modelName": MODEL_NAME},
        embedding_api_key=OPENAI_API_KEY,
    keyspace=DB_KEYSPACE,
    check_exists=False,
)
print(f"* Collection: {collection.full_name}\n")

Parameters:

Name Type Summary

name

str

The name of the collection.

keyspace

Optional[str]

The keyspace where the collection is to be created. If not specified, the database’s working keyspace is used.

dimension

Optional[int]

For vector collections, the dimension of the vectors; that is, the number of their components. If you’re not sure what dimension to set, use whatever dimension vector your embeddings model produces.

metric

Optional[str]

The similarity metric used for vector searches. Allowed values are VectorMetric.DOT_PRODUCT, VectorMetric.EUCLIDEAN or VectorMetric.COSINE (default).

service

Optional[CollectionVectorServiceOptions]

The service definition for vector embeddings. Required for vector collections that generate embeddings automatically. This is an instance of CollectionVectorServiceOptions, which defines the provider and model_name, plus other optional settings like authentication. This parameter can also be a simple dictionary.

indexing

Optional[Dict[str, Any]]

Optional specification of the indexing options for the collection, in the form of a dictionary such as {"deny": […​]} or {"allow": […​]}.

default_id_type

Optional[str]

This sets what type of IDs the API server will generate when inserting documents that do not specify their _id field explicitly. Can be set to any of the values DefaultIdType.UUID, DefaultIdType.OBJECTID, DefaultIdType.UUIDV6, DefaultIdType.UUIDV7, DefaultIdType.DEFAULT.

additional_options

Optional[Dict[str, Any]]

Any further set of key-value pairs that will be added to the "options" part of the payload when sending the Data API command to create a collection.

check_exists

Optional[bool]

Whether to run an existence check for the collection name before attempting to create the collection: If check_exists is True, an error is raised when creating an existing collection. If it is False, the creation is attempted. In this case, for preexisting collections, the command will succeed or fail depending on whether the options match or not.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request.

embedding_api_key

Optional[str]

An optional API key that will be passed to the Data API with each request in the form of an x-embedding-api-key HTTP header. This is useful for collections that are created with an embedding service but without specifying an authentication in the service configuration. This parameter is not stored on the database, it is only used by the Collection instance when issuing reads or writes on the collection.

collection_max_time_ms

Optional[int]

A default timeout, in milliseconds, for the duration of each operation on the collection. Individual timeouts can be provided to each collection method call and will take precedence, with this value being an overall default. Note that for some methods involving multiple API calls (such as delete_many and insert_many), you should provide a timeout with sufficient duration for the operation you’re performing. This parameter is not stored on the database, it is only used by the Collection instance when issuing reads or writes on the collection.

Returns:

Collection - The created collection object, ready to be used to work with the documents in it.

Example response
Collection(name="collection", keyspace="cycling", database=Database(DB_API_ENDPOINT="https://localhost:8181", token="Cassandra:aAbB...", keyspace="cycling"))

Example:

# Create a collection. The default similarity metric is cosine. If you're not
# sure what dimension to set, use whatever dimension vector your embeddings
# model produces.
collection = database.create_collection(
    DB_COLLECTION,
    dimension=5,
    metric=VectorMetric.COSINE,  # or simply "cosine"
    service={"provider": OPEN_AI_PROVIDER, "modelName": MODEL_NAME},
        embedding_api_key=OPENAI_API_KEY,
    keyspace=DB_KEYSPACE,
    check_exists=False,
)
print(f"* Collection: {collection.full_name}\n")

View this topic in more detail on the API Reference.

const collection = await db.createCollection(
  'COLLECTION' {
    keyspace: 'KEYSPACE',
    checkExists: false,
  });

Create a new collection to store vector data.

  const collection = await db.createCollection<Idea>('vector_test', {
    keyspace: DB_KEYSPACE,
    vector: {
      dimension: 5,
      metric: 'cosine',
    },
    checkExists: false
  });
  console.log(* Created collection ${collection.keyspace}.${collection.collectionName});

Create a new collection that generates vector embeddings automatically.

  const collection = await db.createCollection<Idea>('vector_test', {
    keyspace: DB_KEYSPACE,
    vector: {
      service: {
        provider: OPEN_AI_PROVIDER,
        modelName: MODEL_NAME
      },
      dimension: 5,
      metric: 'cosine',
    },
    embeddingApiKey: OPENAI_API_KEY,
    checkExists: false
  });
  console.log(* Created collection ${collection.keyspace}.${collection.collectionName});

A Collection is typed as Collection<Schema> where Schema is the type of the documents in the collection. Operations on the collection will be strongly typed if a specific schema is provided, otherwise remained largely weakly typed if no type is provided, which may be preferred for dynamic data access & operations. It’s up to the user to ensure that the provided type truly represents the documents in the collection.

Parameters:

Name Type Summary

collectionName

string

The name of the collection to create.

vector?

CreateCollectionOptions<Schema>

The options for creating the collection.

  • dimension: The dimension for the vector in the collection.

  • metric: The similarity metric to use for vector search.

  • service.provider: The name of the embeddings provider. Required for vector collections that generate embeddings automatically.

  • service.modelName: The model name for vector embeddings.

  • service.authentication: The shared secret for the embeddings provider using the Astra KMS.

Name Type Summary

vector?

VectorOptions

The vector configuration for the collection, e.g. vector dimension & similarity metric. If not set, collection will not support vector search. If you’re not sure what dimension to set, use whatever dimension vector your embedding model produces.

indexing?

IndexingOptions<Schema>

The indexing configuration for the collection.

defaultId?

DefaultIdOptions

The defaultId configuration for the collection, for when a document does not specify an _id field.

keyspace?

string

Overrides the keyspace where the collection is created. If not set, the database’s working keyspace is used.

checkExists?

boolean

Whether to run an existence check for the collection name before attempting to create the collection.

If it is true or unset, an error is raised when creating an existing collection.

Else, if it’s false, the creation is attempted. In this case, for preexisting collections, the command will succeed or fail depending on whether the options match or not.

embeddingApiKey?

string

An alternative to service.authentication.providerKey for the embeddings provider, using the API key directly instead of the shared secret. Will override the shared secret if both are set.

maxTimeMs?

number

Maximum time in milliseconds the client should wait for the operation to complete.

Returns:

Promise<Collection<Schema>> - A promise that resolves to the created collection object.

Example:

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

// Get a new Db instance
const db = new DataAPIClient('TOKEN').db('DB_API_ENDPOINT');

// Define the schema for the collection
interface User extends VectorDoc {
  name: string,
  age?: number,
}

(async function () {
  // Create a basic untyped non-vector collection
  const users1 = await db.createCollection('users');
  await users1.insertOne({ name: 'John' });

  // Typed collection with custom options in a non-default keyspace
  const users2 = await db.createCollection<User>('users', {
    keyspace: 'KEYSPACE',
    defaultId: {
      type: 'objectId',
    },
    vector: {
      dimension: 5,
      metric: 'cosine',
    },
  });
  await users2.insertOne({ name: 'John' }, { vector: [.12, .62, .87, .16, .72] });
})();

See also: SomeDoc, VectorDoc

To access the Javadoc on those methods consult the Database Javadoc.

// Create a collection
Collection<Document> collectionLyrics =  db.createCollection(collectionName, CollectionOptions.builder()
.build()

// Create collections with vector options
Collection<Document> collectionLyrics =  db.createCollection(collectionName, CollectionOptions.builder()
.vectorDimension(5)
.vectorSimilarity(SimilarityMetric.COSINE)
.build()

// Create a collection with Vector embeddings OPEN AI
Collection<Document> collectionLyrics =  db.createCollection(collectionName, CollectionOptions.builder()
.vectorSimilarity(SimilarityMetric.COSINE)
.vectorDimension(openAiEmbeddingDimension)
.vectorize(openAiProvider, openAiModel)
.build(),
new CommandOptions<>().embeddingAPIKey(openAiKey));

Parameters:

Name Type Summary

collectionName

String

The name of the collection.

dimension

int

The dimension for the vector in the collection. If you’re not sure what dimension to set, use whatever dimension vector your embeddings model produces.

metric

SimilarityMetric

The similarity metric to use for vector search: SimilarityMetric.cosine (default), SimilarityMetric.dot_product, or SimilarityMetric.euclidean.

collectionOptions

CollectionOptions

Fine-grained settings with vector, embedding provider, model name, authentication, indexing, and defaultId options.

clazz

Class<T>

Working with specialized beans for the collection and not the default Document type.

Example:

        // Create a collection
        Collection<Document> collectionLyrics =  db.createCollection(collectionName, CollectionOptions.builder()
        .vectorDimension(5)
        .vectorSimilarity(SimilarityMetric.COSINE)
        .build(),
        System.out.println("5/7 - Collection created");
        // Create a collection with Vector embeddings OPEN AI
        Collection<Document> collectionLyrics =  db.createCollection(collectionName, CollectionOptions.builder()
        .vectorSimilarity(SimilarityMetric.COSINE)
        .vectorDimension(openAiEmbeddingDimension)
        .vectorize(openAiProvider, openAiModel)
        .build(),
        new CommandOptions<>().embeddingAPIKey(openAiKey));
        System.out.println("5/7 - Collection created with OpenAI embeddings");

The vector option

The defaultId option

The Data API defaultId option controls how the Data API will allocate a new _id for each document that does not specify a value in the request.

Once the collection has been created, you cannot change the defaultId option (if entered).

If you include a defaultId option with createCollection, you must set the type. The capitalization is case-sensitive. Specify one of the following:

Type Meaning

objectId

Each document’s generated _id will be an objectId.

uuidv6

Each document’s generated _id will be a Version 6 UUID, which is field compatible with a Version 1 time uuid, but with the ability to be lexicographically sortable.

uuidv7

Each document’s _id will be a Version 7 UUID, which is designed to be a replacement for Version 1 time uuid, and is recommended for use in new systems.

uuid

Each document’s generated _id will be a Version 4 Random UUID. This type is analogous to the uuid type and functions in Apache Cassandra®.

Example:

{
    "createCollection": {
        "name": "vector_collection2",
        "options": {
            "defaultId": {
                "type": "objectId"
            },
            "vector": {
                "dimension": 1024,
                "metric": "cosine"
            }
        }
    }
}

When you add documents to your collection, using Data API commands such as insertOne and insertMany, you would not specify an explicitly numbered _id value (such as "_id": "12") in the request. The server allocates a unique value per document based on the type you indicated in the createCollection command’s defaultId option.

Client apps can detect the use of $objectId or $uuid in the response document and return to the caller the objects that represent the types natively. In this way, client apps can use generated IDs in the methods that are based on Data API operations such as findOneAndUpdate, updateOne, updateMany.

For example, in Python, the client can specify the detected value for a document’s $objectId or $uuid:

# API Response with $objectId
{
"_id": {"$objectId": "57f00cf47958af95dca29c0c"}
    "summary": "Retrieval-Augmented Generation is the process of optimizing the output of a large language model..."
}

# Client returns Dict from collection.find_one()
my_doc = {
    "_id": astrapy.ObjectId("57f00cf47958af95dca29c0c"),
    "summary": "Retrieval-Augmented Generation is the process of optimizing the output of a large language model..."
}

# API Response with $uuid
{
"_id": {"$uuid": "ffd1196e-d770-11ee-bc0e-4ec105f276b8"}
    "summary": "Retrieval-Augmented Generation is the process of optimizing the output of a large language model..."
}

# Client returns Dict from collection.find_one()
my_doc = {
    "_id": UUID("ffd1196e-d770-11ee-bc0e-4ec105f276b8"),
    "summary": "Retrieval-Augmented Generation is the process of optimizing the output of a large language model..."
}

There are many advantages when using generated _id values with documents, versus relying on manually numbered _id values. For example, with generated _id values of type uuidv7:

  • Uniqueness across the database: A generated _id value is designed to be globally unique across the entire database. This uniqueness is achieved through a combination of timestamp, machine identifier, process identifier, and a sequence number. Explicitly numbering documents might lead to clashes unless carefully managed, especially in distributed systems.

  • Automatic generation: The _id values are automatically generated by Hyper-Converged Database (HCD). This means you won’t have to worry about creating and maintaining a unique ID system, reducing the complexity of the code and the risk of errors.

  • Timestamp information: A generated _id value includes a timestamp as its first component, representing the document’s creation time. This can be useful for tracking when a document was created without needing an additional field. In particular, type uuidv7 values provide a high degree of granularity (milliseconds) in timestamps.

  • Avoids manual sequence management: Managing sequential numeric IDs manually can be challenging, especially in environments with high concurrency or distributed systems. There’s a risk of ID collision or the need to lock tables or sequences to generate a new ID, which can affect performance. Generated _id values are designed to handle these issues automatically.

While numeric _id values might be simpler and more human-readable, the benefits of using generated _id values make it a superior choice for most applications, especially those that have many documents.

The indexing option

The Data API createCollection command includes an optional indexing clause.

If you omit the indexing option, by default all properties in the document are indexed when it is added or modified in the database. The index is implemented as a Storage-Attached Index (SAI), which enables Data API queries that filter and/or sort data based on the indexed property.

If you specify the indexing option when you create a collection, you must include one (but not both) of the following: an allow or a deny array.

Pros and cons of selective indexing

It’s important to emphasize the pros and cons of allowing only certain properties to be indexed. While you may want to skip indexing certain properties to increase write-time performance, you’ll need to think ahead. When you create the collection, think about which properties will be important to use in subsequent queries that rely on filtering and/or sort operations. You can only filter and/or sort the properties that have been indexed. Data API returns an error if you attempt to filter or sort a non-indexed property.

The error would have one of these formats:

UNINDEXED_FILTER_PATH("Unindexed filter path"), ...

UNINDEXED_SORT_PATH("Unindexed sort path"), ...

ID_NOT_INDEXED("_id is not indexed"), ...

Example:

UNINDEXED_FILTER_PATH("Unindexed filter path: The filter path ('address.city') is not indexed)"

While weighing the pros and cons of indexed or non-indexed properties in a document, consider the maximum size limits for those properties. Non-indexed properties allow for a much larger quantity of data, to accommodate data such as a blog post’s String content. In comparison, indexed properties are appropriately bound by lower maximum size limits to ensure efficient and performant read operations via the SAI index.

You’ll want to evaluate the pros and cons for each property in a document, and make decisions with the createCollection command’s indexing clause (if specified), based on the read/write and data capacity requirements of your apps.

Of course, test your app’s performance with the database including average and peak loads. If you need to adjust indexing options, try different settings in a newly defined collection and run tests again.

Indexing deny example

Now let’s take an inverse approach with an indexing …​ deny array example in cURL:

curl -s --location \
--request POST ${DB_API_ENDPOINT}/api/json/v1/${DB_KEYSPACE} \
--header "Token: ${DB_APPLICATION_TOKEN}" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data '{
    "createCollection": {
        "name": "vector_collection",
        "options": {
            "vector": {
                "dimension": 5,
                "metric": "cosine"
            },
            "indexing": {
                "deny": [
                    "property1",
                    "property3",
                    "property5.prop5b"
                ]
            }
        }
    }
}' | json_pp

In the preceding example, all the properties in the document are indexed except the ones listed in the deny clause.

Notice how the parent property3 was specified, which means its sub-properties property3.prop3a and property3.prop3b are also not indexed.

However, also notice how the specific sub-property named property5.prop5b was listed on the deny clause; which means property5.prop5b is not indexed, but the parent property5 and the sub-properties property5.prop5a and property5.prop5c are included in the SAI index.

The net result for subsequent update operations:

Property name

Indexed?

property1

No

property2

Yes

property3

No

property3.prop3a

No

property3.prop3b

No

property4

Yes

property5

Yes

property5.prop5a

Yes

property5.prop5b

No

property5.prop5c

Yes

Indexing wildcard examples

The createCollection command’s optional indexing clause provides a convenience wildcard ["*"] in its syntax. For example, in cURL, the following clause means that all properties will be indexed:

{
  "indexing": {
    "allow": ["*"]
  }
}

The preceding example is the equivalent of omitting the indexing clause. Meaning, all properties in the document will be indexed during update operations.

You can use the wildcard character with the deny clause:

{
  "indexing": {
    "deny": ["*"]
  }
}

In the preceding example, no properties are indexed, not even $vector.

List all collections

Retrieve an iterable object over collections. Unless otherwise specified, this implementation refers to the collections in the working keyspace of the database.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

database.list_collections(DB_KEYSPACE)

Parameters:

Name Type Summary

keyspace

Optional[str]

the keyspace to be inspected. If not specified, the database’s working keyspace is used.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request.

Returns:

CommandCursor[CollectionDescriptor] - An iterable over CollectionDescriptor objects.

Example response
# (output below reformatted with indentation for clarity)
# (a single example collection descriptor from the cursor is shown)
[
    ...,
    CollectionDescriptor(
        name='vector_test',
        options=CollectionOptions(
            vector=CollectionVectorOptions(
                dimension=5,
                metric='cosine'
            ),
            indexing={'allow': ['field']}
        )
    ),
    ...
]

Example:

database.list_collections()

View this topic in more detail on the API Reference.

console.log(await db.listCollections());

Parameters:

Name Type Summary

options

ListCollectionsOptions

Options regarding listing collections.

Name Type Summary

nameOnly?

false

If true, only the name of the collection is returned. Else, the full information for each collection is returned. Defaults to true.

keyspace?

string

The keyspace to be inspected. If not specified, the database’s working keyspace is used.

maxTimeMs?

number

Maximum time in milliseconds the client should wait for the operation to complete.

Returns:

Promise<FullCollectionInfo[]> - A promise that resolves to an array of full collection information objects.

Example:

  console.log(await db.listCollections());

To access the Javadoc on those methods consult the Database Javadoc.

db.listCollections().forEach(System.out::println);

Returned Value:

Type Description

Stream<CollectionInfo>

The definition elements of collections.

Example:

        // List all collections
        db.listCollections().forEach(System.out::println);

List collection names

Get the names of the collections as a list of strings. Unless otherwise specified, this refers to the collections in the keyspace the database is set to use.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

database.get_database_admin().list_collection_names()

Get the names of the collections in a specified keyspace of the database.

database.get_database_admin().list_collection_names(keyspace=DB_KEYSPACE)

Parameters:

Name Type Summary

keyspace

Optional[str]

the keyspace to be inspected. If not specified, the database’s working keyspace is used.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request.

Returns:

List[str] - A list of the collection names, in no particular order.

Example response
['vector_test', 'no_vector']

Example:

database.list_collection_names()

View this topic in more detail on the API Reference.

const collectionNames = await db.listCollections({ nameOnly: true });

Get the names of the collections in a specified keyspace of the database.

const collectionNames = await db.listCollections({ nameOnly: true, keyspace: DB_KEYSPACE });

Parameters:

Name Type Summary

options

ListCollectionsOptions

Options regarding listing collections.

Name Type Summary

nameOnly

true

If true, only the name of the collection is returned. Else, the full information for each collection is returned. Defaults to true.

keyspace?

string

The keyspace to be inspected. If not specified, the database’s working keyspace is used.

maxTimeMs?

number

Maximum time in milliseconds the client should wait for the operation to complete.

Returns:

Promise<string[]> - A promise that resolves to an array of the collection names.

Example:

(async function () {
  // Gets just names of all collections in db
  const collections = await db.listCollections({ nameOnly: true });

  for (const collectionName of collections) {
    console.log(`Collection '${collectionName}' exists`);
  }
})();

To access the Javadoc on those methods consult the Database Javadoc.

// Given db Database object, list all collections
Stream<String> collection = listCollectionsNames();

Returned Value:

Type Description

Stream<String>

The names of the collections.

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.definition.CollectionDescriptor;
import com.datastax.astra.client.databases.Database;

import java.util.List;

public class ListCollections {
    public static void main(String[] args) {
        Database db = new DataAPIClient("TOKEN")
                .getDatabase("API_ENDPOINT");

        // Get collection Names
        List<String> collectionNames = db.listCollectionNames();

        // Get Collection information (with options)
        List<CollectionDescriptor> collections = db.listCollections();
        collections.stream().map(CollectionDescriptor::getOptions).forEach(System.out::println);
    }
}

Get a collection

Get a reference to an existing collection.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

collection = database.get_collection("vector_test")

The example above is equivalent to these two alternate notations:

collection1 = database["vector_test"]
collection2 = database.vector_test

The get_collection method will return a Collection object even for collections that don’t exist, so make sure the collection exists first. Your responsibility is to know which collections exist, because the get_collection method does not check for you.

Most astrapy objects have an asynchronous counterpart, for use within the asyncio framework. To get an AsyncCollection, use the get_collection method of instances of AsyncDatabase, or alternatively the to_async method of the synchronous Collection class.

See the AsyncCollection API reference for details about the async API.

Parameters:

Name Type Summary

name

str

The name of the collection.

keyspace

Optional[str]

The keyspace containing the collection. If no keyspace is specified, the general setting for this database is used.

embedding_api_key

Optional[str]

An optional API key that will be passed to the Data API with each request in the form of an x-embedding-api-key HTTP header. This is useful for collections that are created with an embedding service but without specifying authentication in the service configuration.

collection_max_time_ms

Optional[int]

A default timeout, in milliseconds, for the duration of each operation on the collection. Individual timeouts can be provided to each collection method call and will take precedence, with this value being an overall default. Note that for some methods involving multiple API calls (such as delete_many and insert_many), you should provide a timeout with sufficient duration for the operation you’re performing.

Returns:

Collection - An instance of the Collection class corresponding to the specified collection name.

Example response
Collection(name="vector_test", keyspace="cycling", database=Database(DB_API_ENDPOINT="https://localhost:8181", token="Cassandra:aAbB...", keyspace="cycling"))

Example:

from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = my_client.get_database("DB_API_ENDPOINT")

collection = database.get_collection("my_collection")
collection.count_documents({}, upper_bound=100)  # will print e.g.: 41

View this topic in more detail on the API Reference.

const collection = db.collection('DB_COLLECTION');

The collection method will return a Collection object even for collections that don’t exist, so make sure the collection exists first. Your responsibility is to know which collections exist, because the collection method does not check for you.

A Collection is typed as Collection<Schema> where Schema is the type of the documents in the collection. Operations on the collection will be strongly typed if a specific schema is provided, otherwise remained largely weakly typed if no type is provided, which may be preferred for dynamic data access & operations. It’s up to the user to ensure that the provided type truly represents the documents in the collection.

Parameters:

Name Type Summary

collectionName

string

The name of the collection to create.

embeddingApiKey?

string

An alternative to service.authentication.providerKey for the embeddings provider, using the API key directly instead of the shared secret. Will override the shared secret if both are set.

options?

WithKeyspace

Allows you to override which keyspace to use for the collection.

Returns:

Collection<Schema> - An unverified reference to the collection.

Example:

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

// Get a new Db instance
const db = new DataAPIClient('TOKEN').db('DB_API_ENDPOINT');

// Define the schema for the collection
interface User {
  name: string,
  age?: number,
}

(async function () {
  // Basic untyped collection
  const users1 = db.collection('users');
  await users1.insertOne({ name: 'John' });

  // Typed collection from different keyspace with a specific embedding API key
  const users2 = db.collection<User>('users', {
    keyspace: 'DB_KEYSPACE',
    embeddingApiKey: 'EMBEDDINGS_API_KEY',
  });
  await users2.insertOne({ name: 'John' });
})();

See also: SomeDoc, VectorDoc

To access the Javadoc on those methods consult the Database Javadoc.

// Given db Database object, list all collections
Collection<Document> collection = db.getCollection("collection_name");

// Gather collection information
CollectionOptions options = collection.getOptions();

Returned Value:

Type Description

CollectionOptions

The Collection with all metadata (defaultId, vector, indexing) for the collection.

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.CollectionDefinition;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.databases.Database;

public class FindCollection {
  public static void main(String[] args) {
    Database db = new DataAPIClient("TOKEN")
            .getDatabase("API_ENDPOINT");

    // Find a collection
    Collection<Document> collection = db.getCollection("collection_vector1");

    // Gather collection information
    CollectionDefinition options = collection.getDefinition();

    // Check if a collection exists
    boolean collectionExists = db.getCollection("collection_vector2").exists();
  }
}

Drop a collection

Drop (delete) a collection from a database, erasing all data stored in it as well.

  • Python

  • TypeScript

  • Java

View this topic in more detail on the API Reference.

result = db.drop_collection(name_or_collection="vector_collection")

Calling this method is equivalent to invoking the collection’s own method collection.drop(). In that case, trying to use the object afterwards would result in an API error, as it will have become a reference to a non-existent collection.

Parameters:

Name Type Summary

name_or_collection

Union[str, Collection]

either the name of a collection or a Collection instance.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request.

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")
database = my_client.get_database("DB_API_ENDPOINT")

database.list_collection_names()
# prints: ['a_collection', 'my_v_col', 'another_col']
database.drop_collection("my_v_col")  # {'ok': 1}
database.list_collection_names()
# prints: ['a_collection', 'another_col']

View this topic in more detail on the API Reference.

const ok = await db.dropCollection('COLLECTION');

Calling this method is equivalent to invoking the collection’s own method collection.drop(). In that case, trying to use the object afterward would result in an API error, as it will have become a reference to a non-existent collection.

Parameters:

Name Type Summary

name

string

The name of the collection to delete.

options?

DropCollectionOptions

Allows you to override the keyspace & set a maxTimeMs.

Name Type Summary

keyspace?

string

The keyspace containing the collection. If not specified, the database’s working keyspace is used.

maxTimeMS?

number

Maximum time in milliseconds the client should wait for the operation to complete.

Returns:

Promise<boolean> - A promise that resolves to true if the collection was dropped successfully.

Example:

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

// Get a new Db instance
const db = new DataAPIClient('TOKEN').db('DB_API_ENDPOINT');

(async function () {
  // Uses db's default keyspace
  const success1 = await db.dropCollection('users');
  console.log(success1); // true

  // Overrides db's default keyspace
  const success2 = await db.dropCollection('users', {
    keyspace: 'DB_KEYSPACE'
  });
  console.log(success2); // true
})();

To access the Javadoc on those methods consult the Database Javadoc.

// Given db Database object, list all collections
void db.dropCollection("collectionName");

Parameters:

Name Type Summary

collectionName

String

The name of the collection to delete.

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.collections.commands.options.DropCollectionOptions;

public class DropCollection {
  public static void main(String[] args) {
    Database db = new DataAPIClient("TOKEN")
            .getDatabase("API_ENDPOINT");

    // Delete an existing collection
    DropCollectionOptions options = new DropCollectionOptions();
    db.dropCollection("collection_vector2", options);
  }
}

See also

See the Documents reference topic.

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