Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Get started with the Azure Cosmos DB for Apache Cassandra client library for Node.js to store, manage, and query unstructured data. Follow the steps in this guide to create a new account, install a Node.js client library, connect to the account, perform common operations, and query your final sample data.
API reference documentation | Library source code | Package (npm)
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account before you begin.
The latest version of the Azure CLI in Azure Cloud Shell.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
az logincommand.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
- Node.js 22 or newer
Setting up
First, set up the account and development environment for this guide. This section walks you through the process of creating an account, getting its credentials, and then preparing your development environment.
Create an account
Start by creating an API for Apache Cassandra account. Once the account is created, create the keyspace and table resources.
If you don't already have a target resource group, use the
az group createcommand to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --location "<location>"Use the
az cosmosdb createcommand to create a new Azure Cosmos DB for Apache Cassandra account with default settings.az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableCassandra"Create a new keyspace using
az cosmosdb cassandra keyspace createnamedcosmicworks.az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"Create a new JSON object to represent your schema using a multi-line Bash command. Then, use the
az cosmosdb cassandra table createcommand to create a new table namedproducts.schemaJson=$(cat <<EOF { "columns": [ { "name": "id", "type": "text" }, { "name": "name", "type": "text" }, { "name": "category", "type": "text" }, { "name": "quantity", "type": "int" }, { "name": "price", "type": "decimal" }, { "name": "clearance", "type": "boolean" } ], "partitionKeys": [ { "name": "id" } ] } EOF )az cosmosdb cassandra table create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --keyspace-name "cosmicworks" \ --name "product" \ --schema "$schemaJson"
Get credentials
Now, get the password for the client library to use to create a connection to the recently created account.
Use
az cosmosdb showto get the contact point and username for the account.az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{username:name,contactPoint:documentEndpoint}"Record the value of the
contactPointandusernameproperties from the previous commands' output. These properties' values are the contact point and username you use later in this guide to connect to the account with the library.Use
az cosmosdb keys listto get the keys for the account.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"Record the value of the
primaryMasterKeyproperty from the previous commands' output. This property's value is the password you use later in this guide to connect to the account with the library.
Prepare development environment
Then, configure your development environment with a new project and the client library. This step is the last required prerequisite before moving on to the rest of this guide.
Start in an empty folder.
Initialize a new module.
npm init es6 --yesInstall the
cassandra-driverpackage from Node Package Manager (npm).npm install --save cassandra-driverCreate the index.js file.
Start in an empty directory.
Initialize a new module.
npm init es6 --yesInstall the
typescriptpackage from Node Package Manager (npm).npm install --save-dev typescriptInstall the
tsxpackage from npm.npm install --save-dev tsxInstall the
cassandra-driverpackage from npm.npm install --save cassandra-driverInitialize the TypeScript project using the compiler (
tsc).npx tsc --init --target es2017 --module es2022 --moduleResolution nodenextCreate the index.ts file.
Object model
| Description | |
|---|---|
Client |
Represents a specific connection to a cluster |
Mapper |
Cassandra Query Language (CQL) client used to run queries |
Code examples
Authenticate client
Start by authenticating the client using the credentials gathered earlier in this guide.
Open the index.js file in your integrated development environment (IDE).
Import the following types from the
cassandra-drivermodule:cassandracassandra.Clientcassandra.mapping.Mappercassandra.auth.PlainTextAuthProvider
import cassandra from 'cassandra-driver'; const { Client } = cassandra; const { Mapper } = cassandra.mapping; const { PlainTextAuthProvider } = cassandra.auth;Create string constant variables for the credentials collected earlier in this guide. Name the variables
username,password, andcontactPoint.const username = '<username>'; const password = '<password>'; const contactPoint = '<contact-point>';Create another string variable for the region where you created your Azure Cosmos DB for Apache Cassandra account. Name this variable
region.const region = '<azure-region>';Create a new
PlainTextAuthProviderobject with the credentials specified in the previous steps.let authProvider = new PlainTextAuthProvider( username, password );Create a
Clientobject using the credential and configuration variables created in the previous steps.let client = new Client({ contactPoints: [`${contactPoint}:10350`], authProvider: authProvider, localDataCenter: region, sslOptions: { secureProtocol: 'TLSv1_2_method' }, });Asynchronously connect to the cluster.
await client.connect();Create a new mapper targeting the
cosmicworkskeyspace andproducttable. Name the mapperProduct.const mapper = new Mapper(client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });Generate a mapper instance using the
forModelfunction and theProductmapper name.const productMapper = mapper.forModel('Product');
Open the index.ts file in your integrated development environment (IDE).
Import the following types from the
cassandra-drivermodule:cassandra.authcassandra.mappingcassandra.typescassandra.Clientcassandra.ClientOptionscassandra.mapping.Mappercassandra.auth.PlainTextAuthProvider
import { auth, mapping, types, Client, ClientOptions } from 'cassandra-driver'; const { Mapper } = mapping; const { PlainTextAuthProvider } = auth;Create string constant variables for the credentials collected earlier in this guide. Name the variables
username,password, andcontactPoint.const username: string = '<username>'; const password: string = '<password>'; const contactPoint: string = '<contact-point>';Create another string variable for the region where you created your Azure Cosmos DB for Apache Cassandra account. Name this variable
region.const region: string = '<azure-region>';Create a new
PlainTextAuthProviderobject with the credentials specified in the previous steps.let authProvider = new PlainTextAuthProvider( username, password );Create an anonymous object with options that ensures that you're using the transport layer security (TLS) 1.2 protocol.
let sslOptions = { secureProtocol: 'TLSv1_2_method' };Create a
ClientOptionsobject using the credential and configuration variables created in the previous steps.let clientOptions: ClientOptions = { contactPoints: [`${contactPoint}:10350`], authProvider: authProvider, localDataCenter: region, sslOptions: sslOptions };Create a
Clientobject using theclientOptionsvariable in the constructor.let client = new Client(clientOptions);Asynchronously connect to the cluster.
await client.connect();Create a new mapper targeting the
cosmicworkskeyspace andproducttable. Name the mapperProduct.const mapper = new Mapper( client, { models: { 'Product': { tables: ['product'], keyspace: 'cosmicworks' } } });Generate a mapper instance using the
forModelfunction and theProductmapper name.const productMapper = mapper.forModel('Product');
Warning
Complete transport layer security (TLS) validation is disabled in this guide to simplify authentication. For production deployments, fully enable validation.
Upsert data
Next, upsert new data into a table. Upserting ensures that the data is created or replaced appropriately depending on whether the same data already exists in the table.
Create a new object in a variable named
product.const product = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', name: 'Yamba Surfboard', category: 'gear-surf-surfboards', quantity: 12, price: 850.00, clearance: false };Asynchronously invoke the
insertfunction passing in theproductvariable created in the previous step.await productMapper.insert(product);
Define a new interface named
Productwith fields corresponding to the table created earlier in this guide.Type IdstringNamestringCategorystringQuantityintPricedecimalClearanceboolinterface Product { id: string; name: string; category: string; quantity: number; price: number; clearance: boolean; }Tip
In Node.js, you can create this type in another file or create it at the end of the existing file.
Create a new object of type
Product. Store the object in a variable namedproduct.const product: Product = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb', name: 'Yamba Surfboard', category: 'gear-surf-surfboards', quantity: 12, price: 850.00, clearance: false };Asynchronously invoke the
insertfunction passing in theproductvariable created in the previous step.await productMapper.insert(product);
Read data
Then, read data that was previously upserted into the table.
Create an anonymous object named
filter. In this object, include a property namedidwith the same value as the product created earlier in this guide.const filter = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb' };Invoke the
getfunction of the mapper passing in thefiltervariable. Store the result in a variable namedmatchedProduct.let matchedProduct = await productMapper.get(filter);
Create an anonymous object named
filter. In this object, include a property namedidwith the same value as the product created earlier in this guide.const filter = { id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb' };Invoke the
getfunction of the mapper passing in thefiltervariable. Store the result in a variable namedmatchedProductof typeProduct.let matchedProduct: Product = await productMapper.get(filter);
Query data
Finally, use a query to find all data that matches a specific filter in the table.
Create a new string variable named
querywith a CQL query that matches items with the samecategoryfield.const query = ` SELECT * FROM cosmicworks.product WHERE category = :category ALLOW FILTERING `;Create an anonymous object named
params. In this object, include a property namedcategorywith the same value as the product created earlier in this guide.const params = { category: 'gear-surf-surfboards' };Asynchronously invoke the
executefunction passing in both thequeryandparamsvariables as arguments. Store the result'srowsproperty as a variable namedmatchedProducts.let { rows: matchedProducts } = await client.execute(query, params);Iterate over the query results by invoking the
foreachmethod on the array of products.matchedProducts.forEach(product => { // Do something here with each result });
Create a new string variable named
querywith a CQL query that matches items with the samecategoryfield.const query: string = ` SELECT * FROM cosmicworks.product WHERE category = :category ALLOW FILTERING `;Create an anonymous object named
params. In this object, include a property namedcategorywith the same value as the product created earlier in this guide.const params = { category: 'gear-surf-surfboards' };Asynchronously invoke the
executefunction passing in both thequeryandparamsvariables as arguments. Store the result in a variable namedresultof typetypes.ResultSet.let result: types.ResultSet = await client.execute(query, params);Store the result's
rowsproperty as a variable namedmatchedProductsof typeProduct[].let matchedProducts: Product[] = result.rows;Iterate over the query results by invoking the
foreachmethod on the array of products.matchedProducts.forEach((product: Product) => { // Do something here with each result });
Run the code
Run the newly created application using a terminal in your application directory.
node index.js
npx tsx index.ts
Clean up resources
When you no longer need the account, remove the account from your Azure subscription by deleting the resource.
az cosmosdb delete \
--resource-group "<resource-group-name>" \
--name "<account-name>"