📝 NOTE: This content was pulled from PR 311
astra-db-ts is the official TypeScript client for Astra DB Serverless. See common usages below, or check out the GitHub repo.
API reference
The code samples on this page assume the following:
-
You have an active Astra account.
-
You have created a Serverless (vector) database.
-
You have created an application token with the Database Administrator role.
-
You have installed Node.js v16.20.2 or higher. Download and install Node.js.
Use the AstraDB class to work with databases.
Connect to a database using the default namespace.
const db = new AstraDB("*TOKEN*", "*API_ENDPOINT*");Connect to a database using a specific namespace.
const db = new AstraDB("*TOKEN*", "*API_ENDPOINT*", "*NAMESPACE*");AstraDB - An instance of the AstraDB class.
Example response
AstraDB {
_namespace: 'default_keyspace',
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: undefined,
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: HTTP2Strategy {
closed: false,
origin: 'https://********-****-****-****-************.apps.astra.datastax.com',
session: [ClientHttp2Session]
},
userAgent: 'astra-db-ts/0.1.4'
},
_db: Db {
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: undefined,
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: [HTTP2Strategy],
userAgent: 'astra-db-ts/0.1.4'
},
_namespace: 'default_keyspace'
}
}
| Name | Type | Description |
|---|---|---|
token |
|
The authentication token for Astra DB. |
endpoint |
|
The endpoint URL for the database. |
namespace |
|
The namespace to use. If not provided, the default is |
Use the AstraDB and Collection classes to work with collections.
Create a new collection in Astra DB.
const collection = await db.createCollection('collection');Create a new collection to store vector data.
const collection = await db.createCollection('vector_collection', {
"vector": {
"dimension": 3,
"metric": "cosine"
}
});Promise<Collection<Schema>> - A promise that resolves to the result of the operation.
Example response
Collection {
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: 'vector_collection',
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: HTTP2Strategy {
closed: false,
origin: 'https://********-****-****-****-************.apps.astra.datastax.com',
session: [ClientHttp2Session]
},
userAgent: 'astra-db-ts/0.1.4'
},
_collectionName: 'vector_collection',
_db: Db {
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: undefined,
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: [HTTP2Strategy],
userAgent: 'astra-db-ts/0.1.4'
},
_namespace: 'default_keyspace'
}
}
| Name | Type | Description |
|---|---|---|
collectionName |
|
The name of the collection to create. |
options |
|
An optional dictionary of key/value pairs that define additional parameters.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
// Create a new AstraDB instance
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function createCollections() {
// Create a non-vector collection
const collectionSimple = await db.createCollection('collection');
// Create a vector collection
const collectionVector = await db.createCollection('vector_collection', {
"vector": {
"dimension": 3,
"metric": "cosine"
}
});
}
createCollections();Get a reference to a named collection.
const collection = await db.collection('vector_collection');Collection<Schema> - An instance of the Collection class corresponding to the specified collection name.
Example response
Collection {
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: 'vector_collection',
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: HTTP2Strategy {
closed: false,
origin: 'https://********-****-****-****-************.apps.astra.datastax.com',
session: [ClientHttp2Session]
},
userAgent: 'astra-db-ts/0.1.4'
},
_collectionName: 'vector_collection',
_db: Db {
_httpClient: HTTPClient {
baseUrl: 'https://********-****-****-****-************.apps.astra.datastax.com/api/json/v1',
applicationToken: 'AstraCS:************:************',
logSkippedOptions: false,
collection: undefined,
keyspace: 'default_keyspace',
usingHttp2: true,
requestStrategy: [HTTP2Strategy],
userAgent: 'astra-db-ts/0.1.4'
},
_namespace: 'default_keyspace'
}
}
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function getCollectionReference() {
// Get a reference to a collection
const collection = await db.collection('vector_collection');
}
getCollectionReference();|
Note
|
The collection method will return a Collection object even for collections that don’t exist, so make sure the collection exists first.
|
Delete a collection from a database.
const response = await db.dropCollection("vector_collection");Promise<boolean> - A promise that resolves to the result of the delete operation.
Example response
true
Use the Collection class to work with documents.
Insert a single document into a collection.
const response = await collection.insertOne({
name: 'Jane Doe',
$vector: [.08, .68, .30]
});Promise<InsertOneResult<Schema>> - A promise that resolves to a dictionary representing the response from the database after the insert operation.
Example response
{
insertedId: '1'
}
| Name | Type | Description |
|---|---|---|
document |
|
The document to insert into the collection.
This should be an object representing the data structure of the document.
If the object does not contain an |
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function insertDocuments() {
const collection = await db.collection("vector_collection");
// Insert a document with a specific ID
const response1 = await collection.insertOne({
_id: '1',
name: 'John Doe',
$vector: [.12, .52, .32]
});
// Insert a document without specifying an ID (ID is generated automatically)
const response2 = await collection.insertOne({
name: 'Jane Doe',
$vector: [.08, .68, .30]
});
}
insertDocuments();Insert multiple documents into a collection.
const response = await collection.insertMany(
[
{
_id: '1',
name: 'John Doe',
$vector: [.12, .52, .32]
},
{
// _id is generated automatically
name: 'Jane Doe',
$vector: [.08, .68, .30]
}
],
{ ordered: true }
);Promise<InsertManyResult<Schema>> - A promise that resolves to a dictionary representing the response from the database after the insert operation.
Example response
{
insertedCount: 2,
insertedIds: [ '1', '65f39c161410e942a5b9ff45' ]
}
| Name | Type | Description |
|---|---|---|
documents |
|
A list of documents to insert into the collection.
Each item in the array should be an object representing the data structure of the document.
If an object does not contain an |
options |
|
Additional options for the insert operation. |
import { AstraDB, Collection } from '@datastax/astra-db-ts'
// Create a new AstraDB instance
const db = new AstraDB("*TOKEN*", "*API_ENDPOINT*");
async function insertMultipleDocuments() {
const collection = await db.collection("vector_collection");
// Insert multiple documents into the collection
const response = await collection.insertMany(
[
{
_id: '1',
name: 'John Doe',
$vector: [.12, .52, .32]
},
{
// _id is generated automatically
name: 'Jane Doe',
$vector: [.08, .68, .30]
}
],
{ ordered: true }
);
}
insertMultipleDocuments();Retrieve a single document from a collection.
const document = await collection.findOne({
_id: '1'
});Retrieve the most similar document to a given vector.
const document = await collection.findOne({}, {
sort: {
$vector: [.12, .52, .32]
}
});Retrieve only specific fields from a document.
const document = await collection.findOne(
{ _id: '1' },
{ projection: { "name": 1 } }
);Promise<FoundDoc<Schema, GetSim> | null> - A promise that resolves to a dictionary representing the query response or null if no document is found.
Example response
{
_id: '1',
name: 'John Doe',
'$vector': [ 0.12, 0.52, 0.32 ],
'$similarity': 1
}
| Name | Type | Description |
|---|---|---|
filter |
|
Criteria to filter documents. It’s an object where keys are field names and values are conditions for those fields. See Data API operators for the full list of operators. |
options |
|
Additional options for the query.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function findDocuments() {
const collection = await db.collection("vector_collection");
// Retrieve a single document
const document1 = await collection.findOne({
_id: '1'
});
// Retrieve the most similar document
const document2 = await collection.findOne({}, {
sort: {
$vector: [.12, .52, .32]
}
});
// Only retrieve the name field
const document3 = await collection.findOne(
{ _id: '1' },
{ projection: { "name": 1 } }
);
}
findDocuments();Retrieve documents from a collection that match a given filter.
const documents = await collection.find(
{
name: "Jane Doe"
},
{
sort: {
"$vector": [.12, .52, .32]
},
limit: 5
}
);FindCursor<FoundDoc<Schema, GetSim>> - An object that lets you page through the results in the response.
Example response
[
{
_id: '65f3a28328ac16fec882c173',
name: 'Jane Doe',
'$vector': [ 0.08, 0.68, 0.3 ]
}
]
| Name | Type | Description |
|---|---|---|
filter |
|
A dictionary of the fields and field values to use to filter the results. See Data API operators for the full list of operators. |
options |
|
Additional options for the query.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function performSimilaritySearch() {
const collection = await db.collection("vector_collection");
// Define the metadata filter
const metadataFilter = { name: "Jane Doe" };
// Define the search vector and number of documents to return
const options = {
sort: {
"$vector": [.12, .52, .32],
},
limit: 5
};
// Perform a similarity search
const docs = await collection.find(metadataFilter, options).toArray();
}
performSimilaritySearch();Insert or update a single document in a collection.
const results = await collection.updateOne(
{ _id: '1' },
{ $set: { name: "John Smith" } }
);UpdateOneResult - A promise that resolves to the results of the update operation.
Example response
{
modifiedCount: 1,
matchedCount: 1
}
| Name | Type | Description |
|---|---|---|
filter |
|
Criteria to identify the document to update. It’s an object where keys are field names and values are conditions for those fields. See Data API operators for the full list of operators. |
update |
|
The updates to make to the first matched document. |
options |
UpdateOneOptions |
A dictionary of optional settings to use.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function updateDocumentName() {
const collection = await db.collection("vector_collection");
// Insert a document
const insertResults = await collection.insertOne({
_id: '1',
name: 'John Doe'
});
// Update the name of the document
const updateResults = await collection.updateOne(
{ _id: '1' },
{ $set: { name: "John Smith" } },
);
}
updateDocumentName();Insert or update multiple document in a collection.
const updateResults = await collection.updateMany(
{ name: { $exists: false } },
{ $set: { name: 'unknown' } }
);Promise<UpdateOneResult> - A promise that resolves to the results of the update operation.
Example response
{
modifiedCount: 2,
matchedCount: 2
}
| Name | Type | Description |
|---|---|---|
filter |
|
Criteria to identify the documents to update. It’s an object where keys are field names and values are conditions for those fields. See Data API operators for the full list of operators. |
update |
|
The updates to make to all matched documents. It’s an object where keys are field names and values are the new values for those fields. See Data API operators for the full list of property update operators. |
options |
UpdateManyOptions |
A dictionary of optional settings to use.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function updateMultipleDocumentsName() {
const collection = await db.collection("vector_collection");
// Insert some documents
const insertResults = await collection.insertMany([
{ _id: '1', name: 'John Doe', car: 'Renault Twizy' },
{ car: 'BMW 330i' },
{ car: 'McLaren 4x4 SUV' },
]);
// Update the names of some documents
const updateResults = await collection.updateMany(
{ name: { $exists: false } },
{ $set: { name: 'unknown' } }
);
}
updateMultipleDocumentsName();Delete a single document from a collection.
const response = await collection.deleteOne({ _id: '1' });Promise<DeleteOneResult> - A promise that resolves to the results of the delete operation.
Example response
{
deletedCount: 1
}
| Name | Type | Description |
|---|---|---|
filter |
|
Criteria to identify the document to delete. It’s an object where keys are field names and values are conditions for those fields. See Data API operators for the full list of operators. |
options |
DeleteOneOptions |
A dictionary of optional settings to use.
|
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function deleteSingleDocumentByName() {
const collection = await db.collection("vector_collection");
// Insert a document into the collection
const insertResponse = await collection.insertOne({
_id: '1',
name: 'John Doe'
});
// Delete the document from the collection
const deleteResponse = await collection.deleteOne({ _id: '1' });
}
deleteSingleDocumentByName();Delete many documents from a collection.
const result = await collection.deleteMany({ name: "John Doe" });Promise<DeleteManyResult> - A promise that resolves to the results of the delete operation.
Example response
{
deletedCount: 2
}
| Name | Type | Description |
|---|---|---|
filter |
|
Criteria to identify the documents to delete. It’s a record where keys are field names and values are conditions for those fields. See Data API operators for the full list of operators. +
NOTE: If you want to delete all documents, use |
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function deleteDocuments() {
const collection = await db.collection("vector_collection");
// Insert some documents into the collection
const insertResult = await collection.insertMany([
{ _id: '1', name: 'John Doe', car: 'Renault Twizy' },
{ name: 'John Doe', car: 'BMW 330i' },
{ name: 'Jane Doe', car: 'McLaren 4x4 SUV' }
]);
// Delete some documents from the collection
const deleteResult = await collection.deleteMany({ name: "John Doe" });
}
deleteDocuments();Delete all documents in a collection.
await collection.deleteAll();Promise<void> - A promise that resolves when the delete operation is complete.
Example:
import { AstraDB, Collection } from '@datastax/astra-db-ts'
const db = new AstraDB("TOKEN", "API_ENDPOINT");
async function deleteDocuments() {
const collection = await db.collection("vector_collection");
// Insert some documents
const insertResult = await collection.insertMany([
{ _id: '1', name: 'John Doe' },
{ name: 'Jane Doe' }
]);
// Delete all documents in the collection
await collection.deleteAll();
}
deleteDocuments();