Create a collection (TypeScript)

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 promise that resolves to a Collection object. You can use this object to work with documents in the collection.

A Collection is typed as Collection<Schema>, where Schema defaults to SomeDoc (Record<string, any>). Providing the specific Schema type enables stronger typing for collection operations. For more information, see Typing collections and tables.

Parameters

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

Use the createCollection method, which belongs to the Db class.

Method signature
async createCollection<Schema extends SomeDoc = SomeDoc>(
  name: string,
  options?: {
    vector?: CollectionVectorOptions,
    indexing?: CollectionIndexingOptions<Schema>,
    defaultId?: CollectionDefaultIdOptions,
    logging?: DataAPILoggingConfig,
    keyspace?: string,
    serdes?: CollectionSerDesConfig,
    timeoutDefaults?: TimeoutDescriptor,
    timeout?: number | TimeoutDescriptor,
  }
): Collection<Schema>
Name Type Summary

name

string

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

options

CreateCollectionOptions

Optional. The options for this operation. See Properties of options for more details.

Properties of options
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 interface has the following fields:

  • 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.

indexing

CollectionIndexingOptions<Schema>

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 (TypeScript).

For examples, see Create a collection and specify which fields to index and Create a collection and specify which fields shouldn’t be indexed.

Default: All fields of all documents.

defaultId

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:

  • {type: "objectId"}: Each autogenerated _id value is an objectId as provided by the bson library.

  • {type: "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.

  • {type: "uuidv6"}: Each autogenerated _id value is a version 6 UUID. This is field-compatible with version 1 time UUIDs, and it supports lexicographical sorting.

  • {type: "uuid"}: Each autogenerated _id value is a version 4 UUID. This type is analogous to the uuid type and functions in Apache Cassandra®.

For more information, see Document IDs (TypeScript).

Default: Each autogenerated _id value is a string form of a version 4 UUID

keyspace

string

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

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

logging

string

Optional. The configuration for logging events emitted by the DataAPIClient.

serdes

string

Optional. The configuration for serialization/deserialization by the DataAPIClient.

For more information, see Custom Ser/Des.

timeoutDefaults

TimeoutDescriptor

Optional.

The default timeout(s) to apply to operations performed on this Collection instance. You can specify requestTimeoutMs, generalMethodTimeoutMs, and collectionAdminTimeoutMs.

For more information about the TimeoutDescriptor, see TypeScript client internals: TimeoutDescriptor.

timeout

number | TimeoutDescriptor

Optional.

The timeout to apply to this method.

Only collectionAdminTimeoutMs applies to this method. This is the maximum time, in milliseconds, for collection admin operations like creating, dropping, and listing collections.

Default: 60 seconds, unless you specified a different default along the Options Hierarchy.

Examples

The following examples demonstrate how to create a collection.

Create a collection that is not vector-enabled

  • Typed collections

  • Untyped collections

You can manually define a client-side type for your collection to help statically catch errors.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

// Define the type for the collection
interface User {
  name: string;
  age?: number;
}

// Create a collection
(async function () {
  const collection = await database.createCollection<User>(
    "COLLECTION_NAME",
  );
})();

If you don’t pass a type parameter, the collection remains untyped. This is a more flexible but less type-safe option.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

// Create a collection
(async function () {
  const collection = await database.createCollection("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.

  • Typed collections

  • Untyped collections

You can manually define a client-side type for your collection to help statically catch errors.

You can define $vector as an inline field in your interfaces, or you can extend the utility VectorDoc type provided by the client.

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

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

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

(async function () {
  const collection = await database.createCollection<User>(
    "COLLECTION_NAME",
    {
      vector: {
        dimension: 1024,
        metric: "cosine",
        sourceModel: "nv-qa-4",
      },
    },
  );
})();

If you don’t pass a type parameter, the collection remains untyped. This is a more flexible but less type-safe option.

The $vector field must still be number[] or DataAPIVector, or type-related issues will occur.

Consider using a type like VectorDoc & SomeDoc which allows the documents to remain untyped, but still statically requires the $vector field to have the correct type.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

(async function () {
  const collection = await database.createCollection("COLLECTION_NAME", {
    vector: {
      dimension: 1024,
      metric: "cosine",
      sourceModel: "nv-qa-4",
    },
  });
})();

Create a collection and specify the default ID format

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

  • Typed collections

  • Untyped collections

You can manually define a client-side type for your collection to help statically catch errors.

The _id field type should match the defaultId type.

import {
  DataAPIClient,
  ObjectId,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

// Define the type for the collection
interface User {
  _id: ObjectId;
  name: string;
  age?: number;
}

(async function () {
  const collection = await database.createCollection<User>(
    "COLLECTION_NAME",
    {
      defaultId: {
        type: "objectId",
      },
    },
  );
})();

If you don’t pass a type parameter, the collection remains untyped. This is a more flexible but less type-safe option.

However, if you later specify _id when you insert a document, DataStax recommends that it has the same type as the defaultId.

Consider using a type like { id: ObjectId } & SomeDoc which allows the documents to remain untyped, but still statically requires the _id field to have the correct type.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

(async function () {
  const collection = await database.createCollection("COLLECTION_NAME", {
    defaultId: {
      type: "objectId",
    },
  });
})();

Create a collection and specify which fields to index

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

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

(async function () {
  const collection = await database.createCollection("COLLECTION_NAME", {
    indexing: {
      allow: ["city", "country"],
    },
  });
})();

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

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

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get a database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});

(async function () {
  const collection = await database.createCollection("COLLECTION_NAME", {
    indexing: {
      deny: ["city", "country"],
    },
  });
})();

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