Gathering detailed insights and metrics for @datastax/astra-db-ts
Gathering detailed insights and metrics for @datastax/astra-db-ts
Gathering detailed insights and metrics for @datastax/astra-db-ts
Gathering detailed insights and metrics for @datastax/astra-db-ts
npm install @datastax/astra-db-ts
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (99.52%)
JavaScript (0.24%)
Shell (0.17%)
Nix (0.06%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Apache-2.0 License
25 Stars
305 Commits
10 Forks
9 Watchers
4 Branches
19 Contributors
Updated on Jun 14, 2025
Latest Version
2.0.1
Package Id
@datastax/astra-db-ts@2.0.1
Unpacked Size
1.25 MB
Size
207.28 kB
File Count
222
NPM Version
10.8.2
Node Version
20.19.0
Published on
Apr 16, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
astra-db-ts
is a TypeScript client for interacting with DataStax Astra DB.
This README targets v2.0.0+, which expands on the previous 1.x API. Click here for the pre-existing client readme.
Use your preferred package manager to install @datastax/astra-db-ts
.
1npm i @datastax/astra-db-ts # or your favorite package manager's equivalent
If you're using TypeScript, you must use at least version 5.0.0 to use astra-db-ts 2.0
, as it uses modern TypeScript features such as const
type parameters.
1npm i typescript@^5.0.0
Get the API endpoint and your application token for your Astra DB instance @ astra.datastax.com.
1import { DataAPIClient, ObjectId, vector, VectorDoc, oid } from '@datastax/astra-db-ts'; 2 3// Connect to the db 4const client = new DataAPIClient({ logging: 'all' }); 5const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! }); 6 7// The `VectorDoc` interface adds `$vector?: DataAPIVector` as a field to the collection type 8interface Dream extends VectorDoc { 9 _id: ObjectId, 10 summary: string, 11 tags?: string[], 12} 13 14(async () => { 15 // Create the collection with a custom default ID type 16 const collection = await db.createCollection<Dream>('dreams', { 17 defaultId: { type: 'objectId' }, 18 }); 19 20 // Batch-insert some rows into the table. 21 // _id can be optionally provided, or be auto-generated @ the server side 22 await collection.insertMany([{ 23 summary: 'A dinner on the Moon', 24 $vector: vector([0.2, -0.3, -0.5]), 25 }, { 26 summary: 'Riding the waves', 27 $vector: vector([0, 0.2, 1]), 28 tags: ['sport'], 29 }, { 30 _id: oid('674f0f5c1c162131319fa09e'), 31 summary: 'Meeting Beethoven at the dentist', 32 $vector: vector([0.2, 0.6, 0]), 33 }]); 34 35 // Hm, changed my mind 36 await collection.updateOne({ _id: oid('674f0f5c1c162131319fa09e') }, { 37 $set: { summary: 'Surfers\' paradise' } 38 }); 39 40 // Let's see what we've got, by performing a vector search 41 const cursor = collection.find({}) 42 .sort({ vector: vector([0, 0.2, 0.4]) }) 43 .includeSimilarity(true) 44 .limit(2); 45 46 // This would print: 47 // - Surfers' paradise: 0.98238194 48 // - Friendly aliens in town: 0.91873914 49 for await (const result of cursor) { 50 console.log(`${result.summary}: ${result.$similarity}`); 51 } 52 53 // Cleanup (if desired) 54 await collection.drop(); 55})();
1import { DataAPIClient, InferTableSchema, Table, vector } from '@datastax/astra-db-ts'; 2 3// Connect to the db 4const client = new DataAPIClient({ logging: 'all' }); 5const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! }); 6 7// Define the table's schema so we can infer the type of the table automatically (TS v5.0+) 8const DreamsTableSchema = Table.schema({ 9 columns: { 10 id: 'int', 11 summary: 'text', 12 tags: { type: 'set', valueType: 'text' }, 13 vector: { type: 'vector', dimension: 3 }, 14 }, 15 primaryKey: 'id', 16}); 17 18// Infer the TS-equivalent type from the table definition (like zod or arktype). Equivalent to: 19// 20// interface TableSchema { 21// id: number, 22// summary?: string | null, 23// tags?: Set<string>, 24// vector?: DataAPIVector | null, 25// } 26type Dream = InferTableSchema<typeof DreamsTableSchema>; 27 28(async () => { 29 // Create the table if it doesn't already exist 30 // Table will be typed as `Table<Dream, { id: number }>`, where the former is the schema, and the latter is the primary key 31 const table = await db.createTable('dreams', { 32 definition: DreamsTableSchema, 33 ifNotExists: true, 34 }); 35 36 // Create a vector index on the vector column so we can perform ANN searches on the table 37 await table.createVectorIndex('dreams_vector_idx', 'vector', { 38 options: { metric: 'cosine' }, 39 ifNotExists: true, 40 }); 41 42 // Batch-insert some rows into the table 43 const rows: Dream[] = [{ 44 id: 102, 45 summary: 'A dinner on the Moon', 46 vector: vector([0.2, -0.3, -0.5]), 47 }, { 48 id: 103, 49 summary: 'Riding the waves', 50 vector: vector([0, 0.2, 1]), 51 tags: new Set(['sport']), 52 }, { 53 id: 37, 54 summary: 'Meeting Beethoven at the dentist', 55 vector: vector([0.2, 0.6, 0]), 56 }]; 57 await table.insertMany(rows); 58 59 // Hm, changed my mind 60 await table.updateOne({ id: 103 }, { 61 $set: { summary: 'Surfers\' paradise' } 62 }); 63 64 // Let's see what we've got, by performing a vector search 65 const cursor = table.find({}) 66 .sort({ vector: vector([0, 0.2, 0.4]) }) 67 .includeSimilarity(true) 68 .limit(2); 69 70 // This would print: 71 // - Surfers' paradise: 0.98238194 72 // - Friendly aliens in town: 0.91873914 73 for await (const result of cursor) { 74 console.log(`${result.summary}: ${result.$similarity}`); 75 } 76 77 // Cleanup (if desired) 78 await table.drop(); 79})();
astra-db-ts
's abstractions for working at the data and admin layers are structured as depicted by this diagram:
1flowchart TD 2 DataAPIClient -->|".db(endpoint)"| Db 3 DataAPIClient -->|".admin()"| AstraAdmin 4 5 Db --->|".collection(name) 6 .createCollection(name)"| Collection 7 8 Db --->|".table(name) 9 .createTable(name)"| Table 10 11 AstraAdmin -->|".dbAdmin(endpoint) 12 .dbAdmin(id, region)"| DbAdmin 13 14 Db -->|".admin()"| DbAdmin 15 DbAdmin -->|".db()"| Db
Here's a small admin-oriented example:
1import { DataAPIClient } from '@datastax/astra-db-ts'; 2 3// Spawn an admin 4const client = new DataAPIClient('*TOKEN*'); 5const admin = client.admin(); 6 7(async () => { 8 // list info about all databases 9 const databases = await admin.listDatabases(); 10 const dbInfo = databases[0]; 11 console.log(dbInfo.name, dbInfo.id, dbInfo.regions); 12 13 // list keyspaces for the first database 14 const dbAdmin = admin.dbAdmin(dbInfo.id, dbInfo.regions[0].name); 15 console.log(await dbAdmin.listKeyspaces()); 16})();
Like the client hierarchy, the options for each class also exist in a hierarchy.
The general options for parent classes are deeply merged with the options for child classes.
1graph TD 2 DataAPIClientOptions --> AdminOptions 3 DataAPIClientOptions --> DbOptions 4 DbOptions --> CollectionOptions 5 DbOptions --> TableOptions
See DATATYPES.md for a full list of supported datatypes and their TypeScript equivalents.
astra-db-ts
officially supports Data API instances using non-Astra backends, such as Data API on DSE or HCD.
However, while support is native, detection is not; you will have to manually declare the environment at times.
1import { DataAPIClient, UsernamePasswordTokenProvider, DataAPIDbAdmin } from '@datastax/astra-db-ts'; 2 3// You'll need to pass in environment to the DataAPIClient when not using Astra 4const tp = new UsernamePasswordTokenProvider('*USERNAME*', '*PASSWORD*'); 5const client = new DataAPIClient(tp, { environment: 'dse' }); 6const db = client.db('*ENDPOINT*'); 7 8// A common idiom may be to use `dbAdmin.createKeyspace` with `updateDbKeyspace` to initialize the keyspace when necessary 9const dbAdmin = db.admin({ environment: 'dse' }); 10dbAdmin.createKeyspace('...', { updateDbKeyspace: true });
The TokenProvider
class is an extensible concept to allow you to create or even refresh your tokens
as necessary, depending on the Data API backend. Tokens may even be omitted if necessary.
astra-db-ts
provides two TokenProvider
instances by default:
StaticTokenProvider
- This unit provider simply regurgitates whatever token was passed into its constructorUsernamePasswordTokenProvider
- Turns a user/pass pair into an appropriate token for DSE/HCD(See examples/non-astra-backends
for a full example of this in action.)
astra-db-ts
is designed to work in server-side environments, but it can technically work in the browser as well.
However, if, for some reason, you really want to use this in a browser, you may need to install the events
polyfill,
and possibly set up a CORS proxy (such as CORS Anywhere) to forward requests to the Data API.
But keep in mind that this may be very insecure, especially if you're hardcoding sensitive data into your client-side code, as it's trivial for anyone to inspect the code and extract the token (through XSS attacks or otherwise).
See examples/browser
for a full example of browser usage in action, and steps on how to use astra-db-ts
in your own browser application.
astra-db-ts
uses the native fetch
API by default, but it can also work with HTTP/2
using the fetch-h2
module.
However, due to compatability reasons, fetch-h2
is no longer dynamically imported by default, and must be provided to the client manually.
Luckily, it is only a couple of easy steps to get HTTP/2
working in your project:
fetch-h2
by running npm i fetch-h2
.fetch-h2
to the client.1import * as fetchH2 from 'fetch-h2';
2// or `const fetchH2 = require('fetch-h2');`
3
4const client = new DataAPIClient({
5 httpOptions: {
6 client: 'fetch-h2',
7 fetchH2: fetchH2,
8 },
9});
See the using HTTP/2 example for a full example of this in action, and more information on how to use astra-db-ts
with HTTP/2
.
Check out the examples directory for more examples on how to use astra-db-ts
in your own projects.
No vulnerabilities found.
No security vulnerabilities found.