Connect with the Node.js driver
DataStax recommends the Data API and clients for Serverless (Vector) databases. You can use the Data API to perform CQL operations on your table data in Serverless (Vector) databases. DataStax recommends drivers only for Serverless (Non-Vector) databases, legacy applications that rely on a driver, or for CQL functions that aren’t supported by the Data API. For more information, see Connect to a database. |
Because Astra DB is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra DB Serverless databases.
To use the DataStax Node.js driver, you need to install the driver and its dependencies, and then connect the driver to your Astra DB Serverless database. Once connected, you can write scripts that use the driver to run commands against your database.
This quickstart explains how to use the Node.js driver to connect to a Serverless (Vector) database and send some CQL statements to the database. It also includes instructions to migrate an existing DataStax Node.js driver to a version that supports Astra DB.
Prerequisites
-
Install Node.js LTS version with
npm
. -
Download your database’s Secure Connect Bundle (SCB).
For multi-region databases, download the Secure Connect Bundle (SCB) for a region that is geographically close to your application to reduce latency.
If you need to connect to multiple regions in the same application, you need the Secure Connect Bundle (SCB) for each region, and your driver code must instantiate one root object (
session
) for each region. For more information, see Best practices for Cassandra drivers. -
Set the following environment variables:
-
ASTRA_DB_ID
: The database ID. -
KEYSPACE_NAME
: A keyspace in your database, such asdefault_keyspace
. -
APPLICATION_TOKEN
: An application token with the Database Administrator role.
-
Driver authentication methods
There are two driver authentication methods: token
authentication, or clientId
and secret
authentication.
-
Token authentication
-
Client ID and secret authentication
This authentication method is supported and recommended for most recent driver versions.
In your driver authentication code, pass the literal string token
as the username and your application token value (AstraCS:…
) as the password.
For example:
("token", "AstraCS:...")
If you are on an older driver version that doesn’t support token
authentication, then you might need to use clientId
and secret
.
When you generate an application token, download or copy the token.json
that contains the following values:
{
"clientId": "CLIENT_ID",
"secret": "CLIENT_SECRET",
"token": "APPLICATION_TOKEN"
}
In your driver authentication code, pass clientId
as the username and secret
as the password.
For example:
("CLIENT_ID", "SECRET")
For more information, see Token details.
Install the Node.js driver
-
Install the DataStax Node.js driver:
npm install cassandra-driver
If you choose to install an earlier version, make sure you choose a version that is compatible with Astra DB. If you need to query vector data, make sure your chosen version also supports vector data. For more information, see Cassandra drivers supported by DataStax.
Connect the Node.js driver
-
In the root of your Node.js project, create a
connect-database.js
file:cd nodejsProject touch connect-database.js
-
Copy the following connection code into the
connect-database.js
file, and then replacePATH_TO_SCB
with the absolute path to your database’s Secure Connect Bundle (SCB) (secure-connect-DATABASE_NAME.zip
):connect-database.jsconst cassandra = require('cassandra-driver'); const cloud = { secureConnectBundle: "PATH_TO_SCB" }; const authProvider = new cassandra.auth.PlainTextAuthProvider('token', process.env['APPLICATION_TOKEN']); const client = new cassandra.Client({ cloud, authProvider }); async function run() { await client.connect(); // ... }
This code creates a
Client
instance to connect to your Astra DB database, through which you can run commands against your database. -
Save and then run
connect-database.js
with the Node.js runtime to test the connection:node connect-database.js
Run commands with the Node.js driver
After you connect to the database, you can use the driver to perform operations on your database.
Submit a simple statement
The following code connects to an Astra DB database, runs a CQL SELECT
statement, and then prints the output to the console:
// Import libraries and connect to the database
const cassandra = require('cassandra-driver');
const cloud = { secureConnectBundle: "PATH_TO_SCB" };
const authProvider = new cassandra.auth.PlainTextAuthProvider('token', process.env['APPLICATION_TOKEN']);
const client = new cassandra.Client({ cloud, authProvider });
async function run() {
await client.connect();
// Execute a query
const rs = await client.execute('SELECT * FROM system.local');
console.log(Hello from cluster: ${rs.first()['cluster_name']}
);
await client.shutdown();
}
Create a table and vector index
The following code creates a table named vector_test
with columns for an integer id, text, and a 5-dimensional vector.
Then, it creates a custom index on the vector column using dot product similarity function for efficient vector searches.
// ...
const keyspace = 'default_keyspace';
const v_dimension = 5;
await client.execute(`
CREATE TABLE IF NOT EXISTS ${keyspace}.vector_test (id INT PRIMARY KEY,
text TEXT, vector VECTOR<FLOAT,${v_dimension}>);
`);
await client.execute(`
CREATE CUSTOM INDEX IF NOT EXISTS idx_vector_test
ON ${keyspace}.vector_test
(vector) USING 'StorageAttachedIndex' WITH OPTIONS =
{'similarity_function' : 'cosine'};
`);
// ...
Insert data
The following code inserts some rows with embeddings into the vector_test
table.
// ...
const text_blocks = [
{ id: 1, text: 'Chat bot integrated sneakers that talk to you', vector: [0.1, 0.15, 0.3, 0.12, 0.05] },
{ id: 2, text: 'An AI quilt to help you sleep forever', vector: [0.45, 0.09, 0.01, 0.2, 0.11] },
{ id: 3, text: 'A deep learning display that controls your mood', vector: [0.1, 0.05, 0.08, 0.3, 0.6] },
];
for (let block of text_blocks) {
const {id, text, vector} = block;
await client.execute(
`INSERT INTO ${keyspace}.vector_test (id, text, vector) VALUES (${id}, '${text}', [${vector}])`
);
}
// ...
Perform a vector search
The following code performs a vector search to find rows that are close to a specific vector embedding.
// ...
const ann_query = `
SELECT id, text, similarity_cosine(vector, [0.15, 0.1, 0.1, 0.35, 0.55]) as sim
FROM ${keyspace}.vector_test
ORDER BY vector ANN OF [0.15, 0.1, 0.1, 0.35, 0.55] LIMIT 2
`;
const result = await client.execute(ann_query);
result.rows.forEach(row => {
console.log(`[${row.id}] "${row.text}" (sim: ${row.sim.toFixed(4)})`);
});
await client.shutdown();
}
run().catch(console.error);
Upgrade the Node.js driver
Use these steps if you need to upgrade your driver from an earlier version to a version that supports Astra DB:
-
In your existing DataStax Node.js driver code, modify the connection code to use the SCB and
token
authentication. For more information, see Connect the Node.js driver.const { Client } = require('cassandra-driver'); const cloud = { secureConnectBundle: "PATH_TO_SCB" }; const authProvider = new cassandra.auth.PlainTextAuthProvider('token', process.env['APPLICATION_TOKEN']); const client = new cassandra.Client({ cloud, authProvider });