Collections reference
Collections store documents in namespaces.
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
-
Open the
cassandra.yaml
file. -
Find the
sai_indexes_total_failure_threshold
setting and change to the desired number of SAI indexes. -
Save the file.
-
Open the
.env
file. -
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; -
Save the file.
-
Restart the database.
Prerequisites
-
Running cluster.
-
If you use a Data API client, instantiate a
DataAPIClient
object and connect to your database. -
If you use a Data API client, create a namespace.
Create a collection
Create a new collection in a namespace.
-
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"
namespace=DB_NAMESPACE,
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,
namespace=DB_NAMESPACE,
check_exists=False,
)
print(f"* Collection: {collection.full_name}\n")
Parameters:
Name | Type | Summary |
---|---|---|
name |
|
The name of the collection. |
namespace |
|
The namespace where the collection is to be created. If not specified, the database’s working namespace is used. |
dimension |
|
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 |
|
The similarity metric used for vector searches. Allowed values are |
service |
|
The service definition for vector embeddings.
Required for vector collections that generate embeddings automatically.
This is an instance of |
indexing |
|
Optional specification of the indexing options for the collection, in the form of a dictionary such as |
default_id_type |
|
This sets what type of IDs the API server will generate when inserting documents that do not specify their |
additional_options |
|
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 |
|
Whether to run an existence check for the collection name before attempting to create the collection: If |
max_time_ms |
|
A timeout, in milliseconds, for the underlying HTTP request. |
embedding_api_key |
|
An optional API key that will be passed to the Data API with each request
in the form of an |
collection_max_time_ms |
|
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 |
Returns:
Collection
- The created collection object, ready to be used to work with
the documents in it.
Example response
Collection(name="collection", namespace="cycling", database=Database(DB_API_ENDPOINT="https://localhost:8181", token="Cassandra:aAbB...", namespace="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,
namespace=DB_NAMESPACE,
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' {
namespace: 'NAMESPACE',
checkExists: false,
});
Create a new collection to store vector data.
const collection = await db.createCollection<Idea>('vector_test', {
namespace: DB_NAMESPACE,
vector: {
dimension: 5,
metric: 'cosine',
},
checkExists: false
});
console.log(* Created collection ${collection.namespace}.${collection.collectionName}
);
Create a new collection that generates vector embeddings automatically.
const collection = await db.createCollection<Idea>('vector_test', {
namespace: DB_NAMESPACE,
vector: {
service: {
provider: OPEN_AI_PROVIDER,
modelName: MODEL_NAME
},
dimension: 5,
metric: 'cosine',
},
embeddingApiKey: OPENAI_API_KEY,
checkExists: false
});
console.log(* Created collection ${collection.namespace}.${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 |
|
The name of the collection to create. |
vector? |
The options for creating the collection.
|
Options (CreateCollectionOptions
):
Name | Type | Summary |
---|---|---|
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 embeddings model produces. |
||
The indexing configuration for the collection. |
||
The defaultId configuration for the collection, for when a document does not specify an |
||
|
Overrides the namespace where the collection is created. If not set, the database’s working namespace is used. |
|
|
Whether to run an existence check for the collection name before attempting to create the collection. If it is Else, if it’s |
|
|
An alternative to |
|
|
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 namespace
const users2 = await db.createCollection<User>('users', {
namespace: 'NAMESPACE',
defaultId: {
type: 'objectId',
},
vector: {
dimension: 5,
metric: 'cosine',
},
});
await users2.insertOne({ name: 'John' }, { vector: [.12, .62, .87, .16, .72] });
})();
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 |
---|---|---|
|
|
The name of the collection. |
|
|
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. |
|
|
The similarity metric to use for vector search: |
|
|
Fine-grained settings with vector, embedding provider, model name, authentication, indexing, and |
|
|
Working with specialized beans for the collection and not the default |
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 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 |
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 |
---|---|
|
Each document’s generated |
|
Each document’s generated |
|
Each document’s |
|
Each document’s generated |
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, typeuuidv7
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 Of course, test your app’s performance with the database including average and peak loads. If you need to adjust |
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? |
|
No |
|
Yes |
|
No |
|
No |
|
No |
|
Yes |
|
Yes |
|
Yes |
|
No |
|
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 namespace of the database.
-
Python
-
TypeScript
-
Java
View this topic in more detail on the API Reference.
database.list_collections(DB_NAMESPACE)
Parameters:
Name | Type | Summary |
---|---|---|
namespace |
|
the namespace to be inspected. If not specified, the database’s working namespace is used. |
max_time_ms |
|
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 |
Options regarding listing collections. |
Options (ListCollectionsOptions
):
Name | Type | Summary |
---|---|---|
|
If true, only the name of the collection is returned. Else, the full information for each collection is returned. Defaults to true. |
|
|
The namespace to be inspected. If not specified, the database’s working namespace is used. |
|
|
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 |
---|---|
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 namespace 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 namespace of the database.
database.get_database_admin().list_collection_names(namespace=DB_NAMESPACE)
Parameters:
Name | Type | Summary |
---|---|---|
namespace |
|
the namespace to be inspected. If not specified, the database’s working namespace is used. |
max_time_ms |
|
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 namespace of the database.
const collectionNames = await db.listCollections({ nameOnly: true, namespace: DB_NAMESPACE });
Parameters:
Name | Type | Summary |
---|---|---|
options |
Options regarding listing collections. |
Options (ListCollectionsOptions
):
Name | Type | Summary |
---|---|---|
|
If true, only the name of the collection is returned. Else, the full information for each collection is returned. Defaults to true. |
|
|
The namespace to be inspected. If not specified, the database’s working namespace is used. |
|
|
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 |
---|---|
|
The names of the collections. |
Example:
package com.datastax.astra.client.database;
import com.datastax.astra.client.Database;
import com.datastax.astra.client.model.CollectionInfo;
import java.util.stream.Stream;
public class ListCollections {
public static void main(String[] args) {
Database db = new Database("TOKEN", "API_ENDPOINT");
// Get collection Names
Stream<String> collectionNames = db.listCollectionNames();
// Get Collection information (with options)
Stream<CollectionInfo> collections = db.listCollections();
collections.map(CollectionInfo::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 |
Most See the AsyncCollection API reference for details about the async API. |
Parameters:
Name | Type | Summary |
---|---|---|
name |
|
The name of the collection. |
namespace |
|
The namespace containing the collection. If no namespace is specified, the general setting for this database is used. |
embedding_api_key |
|
An optional API key that will be passed to the Data API with each request
in the form of an |
collection_max_time_ms |
|
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 |
Returns:
Collection
- An instance of the Collection class corresponding to the specified collection name.
Example response
Collection(name="vector_test", namespace="cycling", database=Database(DB_API_ENDPOINT="https://localhost:8181", token="Cassandra:aAbB...", namespace="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 |
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 |
|
The name of the collection to create. |
|
An alternative to |
|
options? |
Allows you to override which namespace 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 namespace with a specific embedding API key
const users2 = db.collection<User>('users', {
namespace: 'DB_NAMESPACE',
embeddingApiKey: 'EMBEDDINGS_API_KEY',
});
await users2.insertOne({ name: 'John' });
})();
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 |
---|---|
The Collection with all metadata (defaultId, vector, indexing) for the collection. |
Example:
package com.datastax.astra.client.database;
import com.datastax.astra.client.Collection;
import com.datastax.astra.client.Database;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.CollectionOptions;
public class FindCollection {
public static void main(String[] args) {
Database db = new Database("TOKEN", "API_ENDPOINT");
// Find a collection
Collection<Document> collection = db.getCollection("collection_vector1");
// Gather collection information
CollectionOptions options = collection.getOptions();
// 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 |
Parameters:
Name | Type | Summary |
---|---|---|
name_or_collection |
|
either the name of a collection or a |
max_time_ms |
|
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 |
Parameters:
Name | Type | Summary |
---|---|---|
name |
|
The name of the collection to delete. |
options? |
Allows you to override the namespace & set a |
Options (DropCollectionOptions
):
Name | Type | Summary |
---|---|---|
|
The namespace containing the collection. If not specified, the database’s working namespace is used. |
|
|
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 namespace
const success1 = await db.dropCollection('users');
console.log(success1); // true
// Overrides db's default namespace
const success2 = await db.dropCollection('users', {
namespace: 'DB_NAMESPACE'
});
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 |
---|---|---|
|
|
The name of the collection to delete. |
Example:
package com.datastax.astra.client.database;
import com.datastax.astra.client.Database;
public class DropCollection {
public static void main(String[] args) {
Database db = new Database("API_ENDPOINT", "TOKEN");
// Delete an existing collection
db.dropCollection("collection_vector2");
}
}
See also
See the Documents reference topic.