### Quickstart: Astra DB Collections Example Source: https://github.com/datastax/astra-db-ts/blob/master/README.md Connect to Astra DB, create a collection with a custom ID type, perform batch inserts, update a document, and conduct a vector search. Requires environment variables CLIENT_DB_URL and CLIENT_DB_TOKEN. ```typescript import { DataAPIClient, ObjectId, vector, VectorDoc, oid } from '@datastax/astra-db-ts'; // Connect to the db const client = new DataAPIClient({ logging: 'all' }); const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! }); // The `VectorDoc` interface adds `$vector?: DataAPIVector` as a field to the collection type interface Dream extends VectorDoc { _id: ObjectId, summary: string, tags?: string[], } (async () => { // Create the collection with a custom default ID type const collection = await db.createCollection('dreams', { defaultId: { type: 'objectId' }, }); // Batch-insert some rows into the table. // _id can be optionally provided, or be auto-generated @ the server side await collection.insertMany([{ summary: 'A dinner on the Moon', $vector: vector([0.2, -0.3, -0.5]), }, { summary: 'Riding the waves', $vector: vector([0, 0.2, 1]), tags: ['sport'], }, { _id: oid('674f0f5c1c162131319fa09e'), summary: 'Meeting Beethoven at the dentist', $vector: vector([0.2, 0.6, 0]), }]); // Hm, changed my mind await collection.updateOne({ _id: oid('674f0f5c1c162131319fa09e') }, { $set: { summary: 'Surfers\' paradise' } }); // Let's see what we've got, by performing a vector search const cursor = collection.find({}) .sort({ vector: vector([0, 0.2, 0.4]) }) .includeSimilarity(true) .limit(2); // This would print: // - Surfers' paradise: 0.98238194 // - Friendly aliens in town: 0.91873914 for await (const result of cursor) { console.log(`${result.summary}: ${result.$similarity}`); } // Cleanup (if desired) await collection.drop(); })(); ``` -------------------------------- ### Run All Pre-merge Checks Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/premerge.ts.md This command executes the build, check, test, and example dependency setup scripts sequentially. It is designed to ensure all necessary steps are completed before merging code. ```sh ./scripts/build.ts -update-report ./scripts/check.ts ./scripts/test.ts -bail ./scripts/set-example-client-deps.ts -tar ``` -------------------------------- ### Licensing Header Example Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/check.ts.md This is an example of the required Apache 2.0 licensing header for files in the src and test directories. ```text // Copyright DataStax, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ``` -------------------------------- ### Install @datastax/astra-db-ts Source: https://github.com/datastax/astra-db-ts/blob/master/README.md Install the library using npm or your preferred package manager. ```bash npm i @datastax/astra-db-ts # or your favorite package manager's equivalent ``` -------------------------------- ### Nix-shell and Direnv Support Source: https://github.com/datastax/astra-db-ts/blob/master/DEVGUIDE.md Optional configuration for nix-shell and direnv. If direnv is installed, this setup provides Node.js 20, jq, and adds the scripts directory to the PATH. ```bash direnv block ``` -------------------------------- ### Run Tests Without Setup Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Skip the lengthy setup step for integration tests using the -P flag. This significantly speeds up test execution when the database is already configured. ```sh scripts/test.ts -f integration.documents.tables.ser-des.key-transformer -P ``` -------------------------------- ### Install TypeScript 5.0+ Source: https://github.com/datastax/astra-db-ts/blob/master/README.md Ensure you have TypeScript version 5.0.0 or higher installed, as the library utilizes modern TypeScript features. ```bash npm i typescript@^5.0.0 ``` -------------------------------- ### Run Tests Without Setup Step Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Executes tests while skipping the lengthy setup procedure. This is beneficial for faster iteration when the setup is not critical for the tests being run. ```bash ./scripts/test.ts -P ``` -------------------------------- ### Test File Naming Convention Example Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Example of how test file names map to describe block names for consistency with the test suite's directory structure. ```typescript // ./tests/unnit/documents/tables/ser-des/key-transformer.test.ts describe("unit.documents.tables.ser-des.key-transformer", () => { // tests here! }); ``` -------------------------------- ### Spin up Local Stargate Data API Instance Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/startgate.ts.md Execute this command in a secondary terminal to initiate a local stargate data API instance. Ensure you wait for it to fully start before proceeding. ```shell scripts/startgate.ts ``` -------------------------------- ### List Astra DB Collections in Next.js Source: https://github.com/datastax/astra-db-ts/blob/master/examples/nextjs/README.md This example shows how to initialize the Astra DB client and list all collections in your database within a Next.js API route. Ensure your ASTRA_DB_TOKEN and ASTRA_DB_ENDPOINT are set in your environment variables. The client defaults to using `fetch` when the code is minified, which is typical in Next.js production builds. ```typescript import { DataAPIClient } from '@datastax/astra-db-ts'; // Creates the client. Because the code is minified (when ran), astra-db-ts will default to using // `fetch` as the HTTP client. If you need HTTP/2, please see `examples/http2-when-minified` for more // information on how to use HTTP/2 with Next.js const client = new DataAPIClient(process.env.ASTRA_DB_TOKEN!); const db = client.db(process.env.ASTRA_DB_ENDPOINT!); // You may use the edge runtime as normal as well. HTTP/2 is not supported here, at all. // export const runtime = 'edge'; // Simple example which (attempts to) list all the collections in the database export async function GET(_: Request) { try { const collections = await db.listCollections(); return new Response(JSON.stringify(collections), { headers: { 'Content-Type': 'application/json' }, }); } catch (error: any) { return new Response(JSON.stringify({ error: error.message }), { headers: { 'Content-Type': 'application/json' }, status: 500, }); } } ``` -------------------------------- ### Test File Naming Convention Example Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/check.ts.md Example of a file-level test suite name matching the file path relative to the tests/ directory, with slashes replaced by dots and the .test.ts extension removed. ```typescript describe('unit.documents.utils', () => { // Tests here }); ``` -------------------------------- ### Run Local Tests with Stargate Data API Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/startgate.ts.md After confirming the stargate instance has started, run this command in your main terminal to execute tests against the local environment. ```shell scripts/test.ts -local ``` -------------------------------- ### Configure DataAPIClient for HTTP/2 Source: https://github.com/datastax/astra-db-ts/blob/master/README.md To use HTTP/2, you need to install the 'fetch-h2' module and provide it to the DataAPIClient via the httpOptions.client and httpOptions.fetchH2 properties. ```typescript import * as fetchH2 from 'fetch-h2'; // or `const fetchH2 = require('fetch-h2');` const client = new DataAPIClient({ httpOptions: { client: 'fetch-h2', fetchH2: fetchH2, }, }); ``` -------------------------------- ### Advanced Test Filtering Example Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md An example of a complex test command combining multiple filters for specific test execution. This command includes options for reporting, filtering by tags, parallel execution, and local execution. ```bash scripts/test.ts -R -f integration. -f object-mapping -f explicit -P -L '!isGlobal && e.commandName === "findOne"' -local ``` -------------------------------- ### List Data Type Example Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents an ordered collection of values. ```javascript ['value'] ``` -------------------------------- ### Set Data Type Example Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents an unordered collection of unique values. ```javascript new Set(['value']) ``` -------------------------------- ### Blob Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents binary data. Use DataAPIBlob with a Buffer or the shorthand blob() with a base64 string. ```javascript new DataAPIBlob(Buffer.from(...)) ``` ```javascript blob({ $binary: '' }) ``` -------------------------------- ### Time Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents time of day. Use DataAPITime with a Date object, timestamp, or string, or use the shorthand time(). ```javascript new DataAPITime() ``` ```javascript time(new Date(1734070574056)) ``` ```javascript time('12:34:56') ``` ```javascript time() ``` -------------------------------- ### Date Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents dates. Use DataAPIDate with a Date object, a timestamp, or a string, or use the shorthand date(). ```javascript new DataAPIDate() ``` ```javascript date(new Date(1734070574056)) ``` ```javascript date('1992-05-28') ``` ```javascript date() ``` -------------------------------- ### Build for REPL Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/build.ts.md Use the `-for-repl` flag for a faster build process that only emits CJS code without type checking. This is optimized for REPL startup times. ```bash scripts/build.ts -for-repl ``` -------------------------------- ### Run Build Script Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/build.ts.md Execute the main build script without any specific flags. ```bash scripts/build.ts ``` -------------------------------- ### Accessing Database Client and Info Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/repl.ts.md Use `client` for the database client instance and `db` to retrieve database information. Ensure the database exists before use. ```typescript await db.info() ``` -------------------------------- ### AdminCommandStartedEvent Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Represents an event when an administrative command has started. ```APIDOC ## Class: AdminCommandStartedEvent ### Description Represents an event indicating that an administrative command has started. ### Properties - **timeout** (Partial) - The timeout configuration for the command. ``` -------------------------------- ### Db.table Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Gets a reference to a table, allowing for row-based operations. ```APIDOC ## Db.table ### Description Gets a reference to a table, allowing for row-based operations. This method provides type safety for schema and primary key definitions. ### Method Signature ```typescript table>, RSchema extends SomeRow = FoundRow>(name: string, options?: TableOptions): Table ``` ### Parameters * **name** (string) - Required - The name of the table. * **options** (TableOptions) - Optional - Configuration options for the table reference. ``` -------------------------------- ### Db.collection Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Gets a reference to a collection, allowing for document-based operations. ```APIDOC ## Db.collection ### Description Gets a reference to a collection, allowing for document-based operations. If the collection does not exist, it can be created implicitly on the first write operation. ### Method Signature ```typescript collection = FoundDoc>(name: string, options?: CollectionOptions): Collection ``` ### Parameters * **name** (string) - Required - The name of the collection. * **options** (CollectionOptions) - Optional - Configuration options for the collection reference. ``` -------------------------------- ### Run All Tests Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Execute all tests in the project. This command can take approximately 10 minutes plus prelude test time unless the -P flag is used. ```bash scripts/test.ts ``` -------------------------------- ### Map Data Type Example Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents a collection of key-value pairs. ```javascript new Map([['key', 'value']]) ``` -------------------------------- ### Administer Astra DB with TS Client Source: https://github.com/datastax/astra-db-ts/blob/master/README.md Shows how to initialize the admin client and perform administrative tasks like listing databases and keyspaces. ```typescript import { DataAPIClient } from '@datastax/astra-db-ts'; // Spawn an admin const client = new DataAPIClient('*TOKEN*'); const admin = client.admin(); (async () => { // list info about all databases const databases = await admin.listDatabases(); const dbInfo = databases[0]; console.log(dbInfo.name, dbInfo.id, dbInfo.regions); // list keyspaces for the first database const dbAdmin = admin.dbAdmin(dbInfo.id, dbInfo.regions[0].name); console.log(await dbAdmin.listKeyspaces()); })(); ``` -------------------------------- ### Create Data API Keyspace Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Options for creating a Data API keyspace. ```APIDOC ## CreateDataAPIKeyspaceOptions ### Description Options for creating a Data API keyspace, including replication strategy and whether to update the database keyspace. ### Properties - **replication** (KeyspaceReplicationOptions): Configuration for keyspace replication. - **updateDbKeyspace** (boolean): If true, updates the database keyspace configuration. ``` -------------------------------- ### Boolean Data Type Example Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents true or false values. ```javascript true ``` -------------------------------- ### Timestamp Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents a point in time. Use JavaScript Date objects. ```javascript new Date() ``` ```javascript new Date(1734070574056) ``` ```javascript new Date('...') ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Executes the complete test suite, including longer-running tests. Ensure prerequisites are met before running. ```bash ./scripts/test.ts ``` -------------------------------- ### Initialize Astra DB Client with fetch-h2 Source: https://github.com/datastax/astra-db-ts/blob/master/examples/using-http2/README.md Instantiate the DataAPIClient with explicit httpOptions to use fetch-h2. This is necessary because minification can interfere with dynamic imports of fetch-h2. ```typescript import { DataAPIClient } from '@datastax/astra-db-ts'; import * as fetchH2 from 'fetch-h2'; // Creates the client with the `httpOptions` explicitly set to use our `fetchH2` client as // minification often conflicts with our own dynamic importing of `fetch-h2`. const client = new DataAPIClient(process.env.ASTRA_DB_TOKEN!, { httpOptions: { client: 'fetch-h2', fetchH2 }, }); const db = client.db(process.env.ASTRA_DB_ENDPOINT!); ``` -------------------------------- ### Decimal Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents arbitrary-precision decimals. Use BigNumber with a number or a string. ```javascript new BigNumber(123.4567) ``` ```javascript BigNumber('123456.7e-3') ``` -------------------------------- ### Test Type Flags Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Select specific test suites to run. Use `-all` for comprehensive testing, `-light` for quicker runs, or `-coverage` for generating test coverage statistics. ```bash scripts/test.ts -all ``` ```bash scripts/test.ts -light ``` ```bash scripts/test.ts -coverage ``` -------------------------------- ### String Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents text data. Use single quotes for string literals. ```javascript 'Hello!' ``` -------------------------------- ### Integer Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents standard integers. Use number literals for int, smallint, and tinyint. ```javascript 42 ``` -------------------------------- ### Test Script Usage Syntax Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Provides the general syntax for using the custom test script, outlining available options for test types, filtering, and configuration. ```fortran 1. scripts/test.ts 2. [-all | -light | -coverage] 3. [-fand | -for] [-f/F ]+ [-g/G ]+ [-u] 4. [-w/W ] 5. [-b | -bail] 6. [-R | -no-report] 7. [-c ] 8. [-e ] 9. [-local] 10. [(-l | -logging) | (-L | -logging-with-pred )]] 11. [-P | -skip-prelude] 12. [-watch] ``` -------------------------------- ### Get Table Schema Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Obtain a reference to a specific table with its schema defined. Use this to interact with table data. ```typescript db.table("users"); ``` -------------------------------- ### Test and Publish Astra DB Package Source: https://github.com/datastax/astra-db-ts/blob/master/DEVGUIDE.md Manually run the full test suite before publishing with 'np --no-tests'. This command ensures stability, especially when external providers might cause test failures. ```bash scripts/test.sh -all -w '.*' ``` ```bash np --no-tests ``` -------------------------------- ### Run Light Test Suite Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Executes a subset of the test suite that omits all longer-running tests, resulting in a faster execution time. Ensure prerequisites are met before running. ```bash ./scripts/test.ts -light ``` -------------------------------- ### Get Database Information Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Fetch general information about the connected Astra DB database, including its status and configuration. ```typescript db.info(); ``` -------------------------------- ### Create a Collection in Astra DB Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Use the `collection` method to get a reference to a collection. If the collection does not exist, it will be created. ```typescript db.collection("my_collection"); ``` -------------------------------- ### List Keyspaces Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Lists all keyspaces within the current database. ```APIDOC ## GET /admin/keyspaces ### Description Lists all keyspaces within the current database. ### Method GET ### Endpoint /admin/keyspaces ### Parameters #### Query Parameters - **options** (CommandOptions) - Optional - Options for the command, including timeout settings. ``` -------------------------------- ### Initialize and Use astra-db-ts with DSE Source: https://github.com/datastax/astra-db-ts/blob/master/examples/non-astra-backends/README.md Configure the DataAPIClient for a DSE environment and use UsernamePasswordTokenProvider for authentication. This snippet shows creating a namespace and a collection. ```typescript import { DataAPIClient, UsernamePasswordTokenProvider } from '@datastax/astra-db-ts'; const client = new DataAPIClient({ environment: 'dse' }); const tp = new UsernamePasswordTokenProvider('userName', 'password'); const db = client.db('http://localhost:8181', { token: tp }); const dbAdmin = db.admin({ environment: 'dse' }); (async () => { await dbAdmin.createNamespace('my_keyspace', { updateDbNamespace: true, }); console.log(await dbAdmin.listNamespaces()); const collection = await db.createCollection('my_coll', { checkExists: false, }); })(); ``` -------------------------------- ### Vector Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents a numerical vector. Use DataAPIVector with an array of numbers or the shorthand vector() with an array. ```javascript new DataAPIVector([.1, .2, .3]) ``` ```javascript vector([.1, .2, .3]) ``` -------------------------------- ### Run All Tests with Coverage Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Executes the entire test suite and generates code coverage reports. This command is useful for assessing the completeness of test coverage. ```bash ./scripts/test.ts -coverage ``` -------------------------------- ### BigInt Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents arbitrary-precision integers. Use BigInt() constructor or the 'n' suffix for BigInt literals. ```javascript BigInt('42') ``` ```javascript 42n ``` -------------------------------- ### Build Astra DB Library Source: https://github.com/datastax/astra-db-ts/blob/master/DEVGUIDE.md Run this command to build the library. It cleans the dist directory, updates versioning, compiles TypeScript, generates API reports, and optimizes code size. ```bash npm run build ``` -------------------------------- ### Double and Float Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents floating-point numbers. Supports standard number literals, NaN, Infinity, and -Infinity. ```javascript 3.14 ``` ```javascript NaN ``` ```javascript Infinity ``` ```javascript -Infinity ``` -------------------------------- ### Initialize DataAPIClient for Non-Astra Backends Source: https://github.com/datastax/astra-db-ts/blob/master/README.md When not using Astra, you must manually declare the environment. This snippet shows how to initialize the DataAPIClient with a specific environment like 'dse'. ```typescript import { DataAPIClient, UsernamePasswordTokenProvider, DataAPIDbAdmin } from '@datastax/astra-db-ts'; // You'll need to pass in environment to the DataAPIClient when not using Astra const tp = new UsernamePasswordTokenProvider('*USERNAME*', '*PASSWORD*'); const client = new DataAPIClient(tp, { environment: 'dse' }); const db = client.db('*ENDPOINT*'); // A common idiom may be to use `dbAdmin.createKeyspace` with `updateDbKeyspace` to initialize the keyspace when necessary const dbAdmin = db.admin({ environment: 'dse' }); dbAdmin.createKeyspace('...', { updateDbKeyspace: true }); ``` -------------------------------- ### ObjectId Usage Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Demonstrates how to import and use the ObjectId class and its shorthand `oid` for creating and verifying ObjectIds in collections. ```APIDOC ## ObjectId Usage You can use ObjectIds in collections using the `ObjectId` class (or the `oid` shorthand). Make sure you're importing this from `'@datastax/astra-db-ts'`, and _not_ from `'bson'`. ### Example ```typescript import { ObjectId, oid } from '@datastax/astra-db-ts'; await collection.insertOne({ _id: oid(), // Equivalent to `new ObjectId()` }); const doc = await collection.findOne(); console.log(doc._id instanceof ObjectId); // true ``` ### Creation Methods You can create an `ObjectId` through the constructor function, or through the `oid` shorthand, in three different ways: 1. Provide the objectId as a string (`'507f1f77bcf86cd799439011'`) 2. Provide the timestamp you want the objectID to be based on (`1734070574056`) 3. Leave it `undefined`/`null` to generate a new `ObjectID` based on the current timestamp ### Class Methods From the `ObjectId` class, you can either: - Get the timestamp as a `Date` using `.getTimestamp()` - Get the string representation of the `ObjectId` using `.toString()` - Compare it with another `ObjectId` or `string` using `.equals()` ``` -------------------------------- ### Run Tests with Logging Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Enable detailed logging for debugging requests and understanding Data API interactions. Use -l for general logging or -L with a specific filter. ```sh # Most of the time scripts/test.ts -l # Though sometimes I want something more specific scripts/test.ts -L '!isGlobal && e.commandName === "find"' ``` -------------------------------- ### Incorrect TypeScript Declaration Exports Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/build.ts.md These examples demonstrate incorrect ways to export types from a .d.ts file, which will not work as expected in TypeScript. ```typescript export * from '../astra-db-ts.d.ts'; ``` ```typescript export type * from '../astra-db-ts.d.ts'; ``` -------------------------------- ### List Collections in Astra DB Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Retrieve a list of all collections within the current keyspace. You can opt to get only the names or full descriptors. ```typescript db.listCollections({ nameOnly: true }); ``` ```typescript db.listCollections(); ``` -------------------------------- ### DbAdmin.db Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Returns a `Db` instance for interacting with the database. ```APIDOC ## DbAdmin.db ### Description Returns a `Db` instance that can be used to perform operations within the currently configured keyspace. ### Method Signature ```typescript db(): Db ``` ``` -------------------------------- ### List Tables in Astra DB Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Retrieve a list of all tables within the current keyspace. You can opt to get only the names or full descriptors. ```typescript db.listTables({ nameOnly: true }); ``` ```typescript db.listTables(); ``` -------------------------------- ### Unit Test Shorthand Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Use the `-u` flag as a shorthand for running all unit tests, which also implicitly enables the `-light` flag. ```bash scripts/test.ts -u ``` -------------------------------- ### Create Table Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Options for creating a table in Astra DB, including column definitions and primary key. ```APIDOC ## CreateTableOptions ### Description Options for creating a table, specifying column definitions, primary key, and optional settings like `ifNotExists`. ### Properties - **definition** (CreateTableDefinition): The definition of the table, including columns and primary key. - **ifNotExists** (boolean): If true, the table will only be created if it does not already exist. ``` -------------------------------- ### TimeUUID Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents a time-based UUID. Use UUID with a string or UUID.v1(), or use the shorthand uuid() with a string or uuid.v1(). ```javascript new UUID('...') ``` ```javascript UUID.v1() ``` ```javascript uuid('...') ``` ```javascript uuid.v1() ``` -------------------------------- ### Run Tests on Local Stargate Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Configure tests to run against a local Stargate instance by setting specific environment variables. This requires a separate Stargate process to be running. ```sh # Secondary terminal window to spin up a local stargate data api instance scripts/startgate.ts # Main terminal window after waiting for stargate to start-gate (heh) scripts/test.ts -local ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Execute all tests while collecting coverage statistics using NYC. The -b (bail) flag is enabled by default. This command also takes approximately 10 minutes plus prelude time. ```bash scripts/test.ts -coverage ``` -------------------------------- ### Duration Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents time durations. Use DataAPIDuration with a string or the shorthand duration() with an ISO 8601 duration string. ```javascript new DataAPIDuration('3w') ``` ```javascript duration('P5DT30M') ``` -------------------------------- ### DbAdmin.listKeyspaces Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Lists all keyspaces in the database. ```APIDOC ## DbAdmin.listKeyspaces ### Description Lists all keyspaces available in the database. This operation requires administrative privileges. ### Method Signature ```typescript listKeyspaces(options?: CommandOptions<{ timeout: 'keyspaceAdminTimeoutMs' }>): Promise ``` ### Parameters * **options** (CommandOptions<{ timeout: 'keyspaceAdminTimeoutMs' }>) - Optional - Options for listing keyspaces, including timeout settings. ``` -------------------------------- ### UUID Data Type Examples Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Represents a universally unique identifier. Use UUID with a string or UUID.v4(), or use the shorthand uuid() with a string or uuid.v7(). ```javascript new UUID('...') ``` ```javascript UUID.v4() ``` ```javascript uuid('...') ``` ```javascript uuid.v7() ``` -------------------------------- ### Run Specific Test File Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Execute a single test file by specifying its path relative to the './tests' directory. This is useful for focusing on a particular test case. ```sh scripts/test.ts -f integration.documents.tables.ser-des.key-transformer ``` -------------------------------- ### List User-Defined Types (UDTs) in Astra DB Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Retrieve a list of all User-Defined Types within the current keyspace. You can opt to get only the names or full descriptors. ```typescript db.listTypes({ nameOnly: true }); ``` ```typescript db.listTypes(); ``` -------------------------------- ### Create and Use Vectors Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Shows how to insert a vector using the `vector` shorthand and verifies its type upon retrieval. The `DataAPIVector` class is used for optimal performance. ```typescript import { vector } from '@datastax/astra-db-ts'; await table.insertOne({ vector: vector([.1, .2, .3]), // Equivalent to `new DataAPIVector([.1, .2, .3])` }); const row = await table.findOne(); console.log(row.$vector instanceof DataAPIVector); // true ``` -------------------------------- ### Fetch HTTP Client Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Defines options for the Fetch HTTP client. ```APIDOC ## FetchHttpClientOptions ### Description Interface for configuring the Fetch API based HTTP client. ``` -------------------------------- ### Db.command Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Executes a raw command against the Data API. ```APIDOC ## Db.command ### Description Executes a raw command against the Data API. This is useful for operations not directly exposed by the client library. ### Method Signature ```typescript command(command: Record, options?: RunCommandOptions): Promise ``` ### Parameters * **command** (Record) - Required - The command object to execute. * **options** (RunCommandOptions) - Optional - Options for running the command, such as timeout settings. ``` -------------------------------- ### Override Script Arguments Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/premerge.ts.md Allows overriding default arguments for the build, check, test, and example dependency scripts. Use this to customize the behavior of individual sub-scripts, such as setting the '-local' flag for tests. ```sh ./scripts/premerge.ts -test-args '-b -local -u' ``` -------------------------------- ### Database Creation Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Creates a new Astra database with the specified configuration. ```APIDOC ## POST /databases ### Description Creates a new Astra database. ### Method POST ### Endpoint /databases ### Parameters #### Request Body - **config** (AstraDatabaseConfig) - Required - Configuration for the new database. - **options** (CreateAstraDatabaseOptions) - Optional - Options for database creation. ``` -------------------------------- ### Keyspace Creation Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Creates a new keyspace within a database. ```APIDOC ## POST /admin/keyspaces ### Description Creates a new keyspace within a database. ### Method POST ### Endpoint /admin/keyspaces ### Parameters #### Request Body - **keyspace** (string) - Required - The name of the keyspace to create. - **options** (CreateAstraKeyspaceOptions) - Optional - Options for creating the keyspace. ``` -------------------------------- ### Using Blobs in Tables Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Shows how to insert and verify blob data in tables using the `blob` shorthand or `DataAPIBlob` class. Blobs can be created from Node.js Buffers, ArrayBuffers, or binary representations. ```typescript import { blob, DataAPIBlob } from '@datastax/astra-db-ts'; await table.insertOne({ blob: blob(Buffer.from([0x0, 0x1, 0x2])), // Equivalent to `new DataAPIBlob(...)` }); const row = await collection.findOne(); console.log(row.blob instanceof DataAPIBlob); // true ``` -------------------------------- ### DataAPIEnvironments Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md An enumeration of supported Data API environments. ```APIDOC ## Type: DataAPIEnvironment ### Description Represents the possible environments for the Data API. ### Values - `"astra"` - `"dse"` - `"hcd"` - `"cassandra"` - `"other"` ``` -------------------------------- ### DbAdmin.createKeyspace Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Creates a new keyspace in the database. ```APIDOC ## DbAdmin.createKeyspace ### Description Creates a new keyspace in the database. Keyspaces are logical containers for tables and other database objects. ### Method Signature ```typescript createKeyspace(keyspace: string, options?: CommandOptions<{ timeout: 'keyspaceAdminTimeoutMs' }>): Promise ``` ### Parameters * **keyspace** (string) - Required - The name of the keyspace to create. * **options** (CommandOptions<{ timeout: 'keyspaceAdminTimeoutMs' }>) - Optional - Options for creating the keyspace, including timeout settings. ``` -------------------------------- ### RunCommandOptions Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Options for executing commands against Astra DB, including collection, keyspace, and table specifications. ```APIDOC ## Interface: RunCommandOptions ### Description Defines the options available when running a command against Astra DB. This interface allows specifying the target collection, keyspace, and table, along with other command-specific options. ### Properties - `collection` (string) - Optional - The name of the collection to operate on. - `extraLogInfo` (Record) - Optional - Additional information to include in logs. - `keyspace` (string | null) - Optional - The keyspace (formerly namespace) to target. If null, the default keyspace is used. - `table` (string) - Optional - The name of the table to operate on. ### Deprecated Property - `namespace` (string) - Deprecated - Use `keyspace` instead. The terminology has been updated. ``` -------------------------------- ### Table Create Index Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Options for creating various types of indexes on a table. ```APIDOC ## TableCreateIndexOptions Interface ### Description Options for creating a standard index on a table. ### Properties - `ifNotExists` (boolean, optional): If true, the index creation will not fail if the index already exists. - `options` (TableIndexOptions, optional): Specific options for the index. ``` ```APIDOC ## TableCreateTextIndexOptions Interface ### Description Options for creating a text index on a table. ### Properties - `ifNotExists` (boolean, optional): If true, the index creation will not fail if the index already exists. - `options` (TableTextIndexOptions, optional): Specific options for the text index. ``` ```APIDOC ## TableCreateVectorIndexOptions Interface ### Description Options for creating a vector index on a table. ### Properties - `ifNotExists` (boolean, optional): If true, the index creation will not fail if the index already exists. - `options` (TableVectorIndexOptions, optional): Specific options for the vector index. ``` -------------------------------- ### Create a Keyspace in Astra DB Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Use the `createKeyspace` method to provision a new keyspace within Astra DB. This requires administrative privileges. ```typescript dbAdmin.createKeyspace("my_new_keyspace"); ``` -------------------------------- ### Custom HTTP Client Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Defines options for custom HTTP clients. ```APIDOC ## CustomHttpClientOptions ### Description Interface for defining custom HTTP client implementations. ``` -------------------------------- ### List Databases Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Lists all databases accessible by the current user. ```APIDOC ## GET /databases ### Description Lists all databases accessible by the current user. ### Method GET ### Endpoint /databases ### Parameters #### Query Parameters - **options** (ListAstraDatabasesOptions) - Optional - Options for listing databases, including timeout settings. ``` -------------------------------- ### UUID Usage Source: https://github.com/datastax/astra-db-ts/blob/master/etc/docs/DATATYPES.md Illustrates how to import and use the UUID class and its shorthand `uuid` for generating and managing UUIDs in collections. ```APIDOC ## UUID Usage You can use UUIDs in collections using the `UUID` class (or the `uuid` shorthand). Make sure you're importing this from `'@datastax/astra-db-ts'`, and _not_ from `'uuid'` or `'bson'`. ### Example ```typescript import { UUID, uuid } from '@datastax/astra-db-ts'; await collection.insertOne({ _id: uuid.v4(), // Equivalent to `UUID.v4()` }); const doc = await collection.findOne(); console.log(doc._id instanceof UUID); // true ``` ### Creation Methods You can create a `UUID` through the class, or through the `uuid` shorthand, in a few different ways: 1. By passing the UUID string to `new UUID()` or `uuid()` 2. By using `UUID.v1()`, `.v4()`, `.v6()`, or `.v7()` to generate a new UUID of the respective version 3. By using `uuid.v1()`, `uuid.v4()`, `uuid.v6()`, or `uuid.v7()` to generate a new UUID of the respective version ### Class Methods From the `UUID` class, you can either: - Get the string representation of the `UUID` using `.toString()` - Compare it with another `UUID` or `string` using `.equals()` - Get the version of the `UUID` using `.version` - Get the timestamp of a `v1` or `v7` `UUID` using `.getTimestamp()` - Note that this is [generally not recommended](https://www.rfc-editor.org/rfc/rfc9562.html#section-6.12), but it's there if you really need it ``` -------------------------------- ### Configuring REPL Output and Find Operations Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/repl.ts.md The `cfg` object allows configuration of REPL features. `cfg.plusOutput` controls the verbosity of `+` macro output, and `cfg.fa.project({})` sets the projection for `*fa` utility macros. ```typescript cfg.plusOutput.minimal ``` ```typescript cfg.fa.project({}) ``` -------------------------------- ### Table Configuration and Options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Provides configuration options for tables, including embedding and reranking API keys, logging, and serialization/deserialization settings. ```APIDOC ## Table Configuration ### TableOptions Configuration options for a table, including keyspace, embedding/reranking API keys, logging, and serialization settings. ### TableSerDesConfig Configuration for serialization and deserialization, including codecs and sparse data options. ### TableNominalCodecOpts Options for nominal codecs used in serialization/deserialization. ### TableTypeCodecOpts Options for type codecs used in serialization/deserialization. ``` -------------------------------- ### options Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Retrieves the collection definition, including indexing, lexical, and vector options. ```APIDOC ## options ### Description Retrieves the collection definition, including indexing, lexical, and vector options. ### Method `options(options?: CommandOptions<{ timeout: 'collectionAdminTimeoutMs'; }>): Promise>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage (assuming collection is already initialized) const collectionOptions = await collection.options(); console.log(collectionOptions); ``` ### Response #### Success Response (200) - **CollectionDefinition**: An object containing the collection's definition and configuration. ``` -------------------------------- ### AdminOptions Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Configuration options for administrative operations. ```APIDOC ## Interface: AdminOptions ### Description Provides configuration options for administrative tasks. ### Properties - **adminToken** (string | TokenProvider | null | undefined) - The token for administrative authentication. - **astraEnv** ('dev' | 'prod' | 'test' | undefined) - The Astra environment to target. - **endpointUrl** (string | undefined) - The specific endpoint URL for Astra DB. - **logging** (LoggingConfig | undefined) - Configuration for logging administrative operations. - **timeoutDefaults** (Partial | undefined) - Default timeout settings for commands. ``` -------------------------------- ### List Astra DB Collections in Browser Source: https://github.com/datastax/astra-db-ts/blob/master/examples/browser/README.md This TypeScript code snippet demonstrates how to initialize the Astra DB client in a browser environment and list all collections in a database. It requires an API key and database endpoint, prefixed with a CORS proxy URL. User input is used for the API key, and environment variables for the endpoint and proxy. ```typescript import { DataAPIClient } from '@datastax/astra-db-ts'; const client = new DataAPIClient(prompt('Enter your AstraDB API key: ')); const db = client.db(`${import.meta.env.CORS_PROXY_URL}${import.meta.env.ASTRA_DB_ENDPOINT}`); const app = document.querySelector('#app')!; app.innerHTML = '

Loading...

'; db.listCollections().then((collections) => { app.innerHTML = `${JSON.stringify(collections, null, 2)}`; }); ``` -------------------------------- ### Db.listTables Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Lists all tables in the current keyspace. ```APIDOC ## Db.listTables ### Description Lists all tables in the current keyspace. Can return just names or full descriptors. ### Method Signature ```typescript listTables(options: ListTablesOptions & { nameOnly: true }): Promise listTables(options?: ListTablesOptions & { nameOnly?: false }): Promise ``` ### Parameters * **options** (ListTablesOptions & { nameOnly: true } | ListTablesOptions & { nameOnly?: false }) - Optional - Options for listing tables, including whether to return only names. ``` -------------------------------- ### Import Custom Test Functions Source: https://github.com/datastax/astra-db-ts/blob/master/scripts/docs/test.ts.md Import the custom test functions describe, it, parallel, and background from the test library. ```typescript import { background, describe, it, parallel } from '@/tests/testlib'; ``` -------------------------------- ### GenericFindOneAndUpdateOptions Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Options for the findOneAndUpdate operation, supporting projection, return document control, sorting, and upsert functionality. ```APIDOC ## GenericFindOneAndUpdateOptions ### Description Options for the findOneAndUpdate operation. ### Properties - **projection** (Projection) - Optional - Specifies which fields to include or exclude. - **returnDocument** ('before' | 'after') - Optional - Determines whether to return the document before or after the update. - **sort** (Sort) - Optional - Specifies the sort order for selecting the document. - **upsert** (boolean) - Optional - If true, creates a new document if no document matches the filter. ``` -------------------------------- ### Db.createTable Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Creates a new table in the database. ```APIDOC ## Db.createTable ### Description Creates a new table in the database. Supports defining the table schema and primary keys using generic types for type safety. ### Method Signature ```typescript createTable(name: string, options: CreateTableOptions): Promise, InferTablePrimaryKey>> createTable>, RSchema extends SomeRow = FoundRow>(name: string, options: CreateTableOptions): Promise> ``` ### Parameters * **name** (string) - Required - The name of the table to create. * **options** (CreateTableOptions | CreateTableOptions) - Required - Options for creating the table, including schema definition, primary keys, and table options. ``` -------------------------------- ### DbOptions Interface Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Configuration options for connecting to and interacting with Astra DB. ```APIDOC ## DbOptions ### Description Configuration options for connecting to and interacting with Astra DB. ### Properties - **dataApiPath** (string) - Optional - The base path for the Data API. - **keyspace** (string | null) - Optional - The default keyspace to use. - **logging** (LoggingConfig) - Optional - Configuration for logging. - **serdes** (DbSerDesConfig) - Optional - Serialization and deserialization configuration. - **timeoutDefaults** (Partial) - Optional - Default timeout settings. - **token** (string | TokenProvider | null) - Optional - Authentication token or provider. ``` -------------------------------- ### StaticTokenProvider Class Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Provides a static token for authentication. ```APIDOC ## StaticTokenProvider Class ### `constructor(token: string)` Initializes the provider with a static token. ### `getToken(): string` Returns the static token. ### `toHeadersProvider(): ParsedHeadersProviders` Converts the token provider to a headers provider. ``` -------------------------------- ### Manage Tables with Astra DB TS Client Source: https://github.com/datastax/astra-db-ts/blob/master/README.md Demonstrates creating a table with a schema, adding a vector index, inserting and updating data, performing a vector search, and cleaning up. ```typescript import { DataAPIClient, InferTableSchema, Table, vector } from '@datastax/astra-db-ts'; // Connect to the db const client = new DataAPIClient({ logging: 'all' }); const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! }); // Define the table's schema so we can infer the type of the table automatically (TS v5.0+) const DreamsTableSchema = Table.schema({ columns: { id: 'int', summary: 'text', tags: { type: 'set', valueType: 'text' }, vector: { type: 'vector', dimension: 3 }, }, primaryKey: 'id', }); // Infer the TS-equivalent type from the table definition (like zod or arktype). Equivalent to: // // interface TableSchema { // id: number, // summary?: string | null, // tags?: Set, // vector?: DataAPIVector | null, // } type Dream = InferTableSchema; (async () => { // Create the table if it doesn't already exist // Table will be typed as `Table`, where the former is the schema, and the latter is the primary key const table = await db.createTable('dreams', { definition: DreamsTableSchema, ifNotExists: true, }); // Create a vector index on the vector column so we can perform ANN searches on the table await table.createVectorIndex('dreams_vector_idx', 'vector', { options: { metric: 'cosine' }, ifNotExists: true, }); // Batch-insert some rows into the table const rows: Dream[] = [{ id: 102, summary: 'A dinner on the Moon', vector: vector([0.2, -0.3, -0.5]), }, { id: 103, summary: 'Riding the waves', vector: vector([0, 0.2, 1]), tags: new Set(['sport']), }, { id: 37, summary: 'Meeting Beethoven at the dentist', vector: vector([0.2, 0.6, 0]), }]; await table.insertMany(rows); // Hm, changed my mind await table.updateOne({ id: 103 }, { $set: { summary: 'Surfers\' paradise' } }); // Let's see what we've got, by performing a vector search const cursor = table.find({}) .sort({ vector: vector([0, 0.2, 0.4]) }) .includeSimilarity(true) .limit(2); // This would print: // - Surfers' paradise: 0.98238194 // - Friendly aliens in town: 0.91873914 for await (const result of cursor) { console.log(`${result.summary}: ${result.$similarity}`); } // Cleanup (if desired) await table.drop(); })(); ``` -------------------------------- ### Event Emitter Methods Source: https://github.com/datastax/astra-db-ts/blob/master/etc/astra-db-ts.api.md Methods for managing event listeners on the client. ```APIDOC ## once ### Description Registers a one-time event listener that will be called only the next time the event is fired. ### Parameters - **eventName** (E) - The name of the event to listen for. - **listener** ((event: Events[E]) => void) - The callback function to execute when the event is fired. ### Returns `() => void` - A function to unregister the listener. ``` ```APIDOC ## removeAllListeners ### Description Removes all event listeners for a specific event, or all listeners if no event name is provided. ### Parameters - **eventName** (E) - Optional. The name of the event for which to remove listeners. ```