Create a collection (Python)

Creates a new collection in a database.

Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart.

Result

Creates a collection with the specified parameters.

Returns a Collection object. You can use this object to work with documents in the collection.

Unless you specify the document_type parameter, the collection is typed as Collection[dict]. For more information, see Typing support.

Parameters

You cannot edit a collection’s definition after you create the collection.

The signature of this method changed in Python client version 2.0.

If you are using an earlier version, DataStax recommends upgrading to the latest version. For more information, see Data API client upgrade guide (Python).

Use the create_collection method, which belongs to the astrapy.Database class.

Method signature
create_collection(
  name: str,
  *,
  definition: CollectionDefinition | dict[str, Any] | None,
  document_type: type[Any],
  keyspace: str,
  collection_admin_timeout_ms: int,
  spawn_api_options: APIOptions,
) -> Collection

Most astrapy objects have an asynchronous counterpart for use within the asyncio framework. To get an AsyncCollection, use the create_collection method of instances of AsyncDatabase, or use the to_async method of the synchronous Collection class. For more information, see AsyncCollection.

Name Type Summary

name

str

The name of the new collection.

Collection names must follow these rules:

  • Can contain letters, numbers, and underscores

  • Cannot exceed 48 characters

  • Must be unique within the keyspace

definition

CollectionDefinition

Optional. The full configuration for the collection. See Properties of CollectionDefinition and Examples for more details.

document_type

type

Optional. A formal specifier for the type checker. If provided, document_type must match the type hint specified in the assignment. For more information, see Typing support.

Default: Collection[dict]

keyspace

str

Optional if you specified a working keyspace when you created the Database object. The keyspace in which to create the collection.

Default: The working keyspace set when you created the Database object, if one was provided.

collection_admin_timeout_ms

int

Optional. A timeout, in milliseconds, to impose on the underlying API request. If not provided, the corresponding Database defaults apply.

spawn_api_options

APIOptions

Optional. A complete or partial specification of the APIOptions to override the defaults inherited from the Database. Use this to customize the interaction of the Python client with the collection. For example, you can change the serialization/deserialization options or default timeouts.

If APIOptions is passed together with a named parameter such as a timeout, the latter takes precedence over the corresponding spawn_api_options setting.

Properties of CollectionDefinition
Name Type Summary

vector

CollectionVectorOptions

Optional. The vector configuration for the collection. This includes things like the vector dimension, similarity metric, and source model.

Required for vector search.

The CollectionVectorOptions class has the following attributes:

  • dimension (int): The dimension for vector embeddings in the collection. This should match the dimension of the vector that your embedding model produces. Optional if you specify a vector.service.modelName value that has a default dimension value.

  • metric (string): Optional. The similarity metric to use for vector search. Can be one of the values in astrapy.constants.VectorMetric: COSINE, DOT_PRODUCT, EUCLIDEAN.

  • sourceModel (string): Optional. The model used to generate the vector embeddings. This enables certain vector optimizations on the index. Can be one of: ada002, bert, cohere-v3, gecko, nv-qa-4, openai-v3-large, openai-v3-small, other.

lexical

CollectionLexicalOptions

Optional. The lexical search configuration for the collection.

Only collections in databases in the AWS us-east-2 region support this parameter.

The CollectionLexicalOptions object has the following properties:

Default: A CollectionLexicalOptions object with an enabled value of True and an analyzer value of "standard", which corresponds to the standard Apache Lucene™ analyzer.

indexing

dict

Optional. The selective indexing configuration for the collection.

You must use & to escape any . or & in field names in the indexing clause. You cannot use & to escape any other characters. Dot notation, which is used to reference nested fields, should not be escaped. For more information, see Work with . and & in field names (Python).

Default: All fields of all documents.

default_id

CollectionDefaultIDOptions

Optional. Specifies the default ID type for documents in the collection. This is used when you insert a document without an _id field.

Can be one of:

  • CollectionDefaultIDOptions(DefaultIdType.OBJECTID): Each autogenerated _id value is an objectId as provided by the bson library.

  • CollectionDefaultIDOptions(DefaultIdType.UUIDV7): Each autogenerated _id value is a version 7 UUID. This is designed as a replacement for version 1 time UUID, and it is recommended for use in new systems.

  • CollectionDefaultIDOptions(DefaultIdType.UUIDV6): Each autogenerated _id value is a version 6 UUID. This is field-compatible with version 1 time UUIDs, and it supports lexicographical sorting.

  • CollectionDefaultIDOptions(DefaultIdType.UUID): Each autogenerated _id value is a version 4 UUID. This type is analogous to the uuid type and functions in Apache Cassandra®.

  • CollectionDefaultIDOptions(DefaultIdType.DEFAULT): Each autogenerated _id value is a string form of a version 4 UUID.

For more information, see Document IDs (Python).

Default: CollectionDefaultIDOptions(DefaultIdType.DEFAULT)

Examples

The following examples demonstrate how to create a collection.

Create a collection that is not vector-enabled

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get a database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection = database.create_collection("COLLECTION_NAME")

Create a collection that can store vector embeddings

Collections that are vector-enabled can store vector embeddings in the reserved $vector field and work with vector search.

For optimal vector search results, you should specify the dimension, metric, and source model of your vector embeddings. All vector embeddings in a collection should be generated by the same model with the same dimensions. The source model can be one of: ada002, bert, cohere-v3, gecko, nv-qa-4, openai-v3-large, openai-v3-small, other.

The Python client supports multiple ways to create a collection:

  • You can define the collection parameters in a CollectionDefinition object and then create the collection from the CollectionDefinition object.

  • You can use a fluent interface to build the collection definition and then create the collection from the definition.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

  • CollectionDefinition object

  • Fluent interface

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, VectorMetric
from astrapy.info import CollectionDefinition, CollectionVectorOptions

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = CollectionDefinition(
    vector=CollectionVectorOptions(
        dimension=1024, metric=VectorMetric.COSINE, source_model="nv-qa-4"
    )
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, VectorMetric
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

collection_definition = (
    CollectionDefinition.builder()
    .set_vector_dimension(1024)
    .set_vector_metric(VectorMetric.COSINE)
    .set_vector_source_model("nv-qa-4")
    .build()
)

collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)

Create a collection that supports lexicographical matching

If you want to use lexicographical matching to find documents in your collection, you must create a collection that has lexical enabled. Your collection must also be in a database in the AWS us-east-2 region.

Lexical is enabled by default when you create a collection in a database in the AWS us-east-2 region, but you can optionally configure the lexical analyzer.

For configuration details about the lexical analyzer, see Configure and use SAI text analyzers with CQL. The following example uses a configuration suitable for English text.

The Python client supports multiple ways to create a collection:

  • You can define the collection parameters in a CollectionDefinition object and then create the collection from the CollectionDefinition object.

  • You can use a fluent interface to build the collection definition and then create the collection from the definition.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

  • CollectionDefinition object

  • Fluent interface

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
    CollectionDefinition,
    CollectionLexicalOptions,
)

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)

# Create a collection
collection_definition = CollectionDefinition(
    lexical=CollectionLexicalOptions(
        analyzer={
            "tokenizer": {"name": "standard", "args": {}},
            "filters": [
                {"name": "lowercase"},
                {"name": "stop"},
                {"name": "porterstem"},
                {"name": "asciifolding"},
            ],
            "charFilters": [],
        },
        enabled=True,
    ),
)
collection = database.create_collection(
    "COLLECTION_NAME",
    definition=collection_definition,
)
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)

# Create a collection
collection_definition = (
    CollectionDefinition.builder()
    .set_lexical(
        {
            "tokenizer": {"name": "standard", "args": {}},
            "filters": [
                {"name": "lowercase"},
                {"name": "stop"},
                {"name": "porterstem"},
                {"name": "asciifolding"},
            ],
            "charFilters": [],
        }
    )
    .build()
)
collection = database.create_collection(
    "COLLECTION_NAME",
    definition=collection_definition,
)

Create a collection and specify the default ID format

For more information about the default ID format, see Document IDs (Python). For allowed values, see the Parameters.

The Python client supports multiple ways to create a collection:

  • You can define the collection parameters in a CollectionDefinition object and then create the collection from the CollectionDefinition object.

  • You can use a fluent interface to build the collection definition and then create the collection from the definition.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

  • CollectionDefinition object

  • Fluent interface

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import DefaultIdType, Environment
from astrapy.info import CollectionDefaultIDOptions, CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = CollectionDefinition(
    default_id=CollectionDefaultIDOptions(DefaultIdType.OBJECTID)
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import DefaultIdType, Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = (
    CollectionDefinition.builder()
    .set_default_id(DefaultIdType.OBJECTID)
    .build()
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)

Create a collection and specify which fields to index

For more information about selective indexing, see Indexes in collections (Python).

The Python client supports multiple ways to create a collection:

  • You can define the collection parameters in a CollectionDefinition object and then create the collection from the CollectionDefinition object.

  • You can use a fluent interface to build the collection definition and then create the collection from the definition.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

  • CollectionDefinition object

  • Fluent interface

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = CollectionDefinition(
    indexing={"allow": ["city", "country"]}
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = (
    CollectionDefinition.builder()
    .set_indexing("allow", ["city", "country"])
    .build()
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)

Create a collection and specify which fields shouldn’t be indexed

For more information about selective indexing, see Indexes in collections (Python).

The Python client supports multiple ways to create a collection:

  • You can define the collection parameters in a CollectionDefinition object and then create the collection from the CollectionDefinition object.

  • You can use a fluent interface to build the collection definition and then create the collection from the definition.

The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.

  • CollectionDefinition object

  • Fluent interface

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = CollectionDefinition(
    indexing={"deny": ["city", "country"]}
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import CollectionDefinition

# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)

# Create a collection
collection_definition = (
    CollectionDefinition.builder()
    .set_indexing("deny", ["city", "country"])
    .build()
)
collection = database.create_collection(
    "COLLECTION_NAME", definition=collection_definition
)

Client reference

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

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: Contact IBM