Quickstart: Build a Cassandra app with Node.js and Azure Cosmos DB

This quickstart shows how to use Node.js and the Azure Cosmos DB Cassandra API to build a profile app by cloning an example from GitHub. This quickstart also shows you how to use the web-based Azure portal to create an Azure Cosmos DB account.

Azure Cosmos DB is Microsoft's globally distributed multi-model database service. You can quickly create and query document, table, key-value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

Prerequisites

If you don't have an Azure subscription, create a free account before you begin. Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.

In addition, you need:

Create a database account

Before you can create a document database, you need to create a Cassandra account with Azure Cosmos DB.

  1. In a new browser window, sign in to the Azure portal.

  2. Select Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same unique name as provided in ID
    Select Create new. Then enter a new resource-group name for your account. For simplicity, use the same name as your ID.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can use only lowercase letters, numbers, and the hyphen (-) character. It must be between 3 and 31 characters in length.
    API Cassandra The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Select Cassandra because in this quickstart you are creating a table that works with the Cassandra API.

    Learn more about the Cassandra API.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.

    Select Review+Create. You can skip the Network and Tags section.

    The new account page for Azure Cosmos DB

  4. The account creation takes a few minutes. Wait for the portal to display the page saying Congratulations! Your Azure Cosmos DB account was created.

Clone the sample application

Now let's clone a Cassandra API app from GitHub, set the connection string, and run it. You see how easy it is to work with data programmatically.

  1. Open a command prompt. Create a new folder named git-samples. Then, close the command prompt.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash. Use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-cassandra-nodejs-getting-started.git
    

Review the code

This step is optional. If you're interested to learn how the code creates the database resources, you can review the following snippets. The snippets are all taken from the uprofile.js file in the C:\git-samples\azure-cosmos-db-cassandra-nodejs-getting-started folder. Otherwise, you can skip ahead to Update your connection string.

  • The username and password values were set using the connection string page in the Azure portal. The path\to\cert provides a path to an X509 certificate.

    var ssl_option = {
         cert : fs.readFileSync("path\to\cert"),
         rejectUnauthorized : true,
         secureProtocol: 'TLSv1_2_method'
         };
    const authProviderLocalCassandra = new cassandra.auth.PlainTextAuthProvider(config.username, config.password);
    
  • The client is initialized with contactPoint information. The contactPoint is retrieved from the Azure portal.

    const client = new cassandra.Client({contactPoints: [config.contactPoint], authProvider: authProviderLocalCassandra, sslOptions:ssl_option});
    
  • The client connects to the Azure Cosmos DB Cassandra API.

    client.connect(next);
    
  • A new keyspace is created.

    function createKeyspace(next) {
        var query = "CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {\'class\': \'NetworkTopologyStrategy\', \'datacenter1\' : \'1\' }";
        client.execute(query, next);
        console.log("created keyspace");    
    }
    
  • A new table is created.

    function createTable(next) {
     var query = "CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)";
         client.execute(query, next);
         console.log("created table");
    },
    
  • Key/value entities are inserted.

    ...
       {
          query: 'INSERT INTO  uprofile.user  (user_id, user_name , user_bcity) VALUES (?,?,?)',
          params: [5, 'IvanaV', 'Belgaum', '2017-10-3136']
        }
    ];
    client.batch(queries, { prepare: true}, next);
    
  • Query to get all key values.

    var query = 'SELECT * FROM uprofile.user';
    client.execute(query, { prepare: true}, function (err, result) {
      if (err) return next(err);
      result.rows.forEach(function(row) {
        console.log('Obtained row: %d | %s | %s ',row.user_id, row.user_name, row.user_bcity);
      }, this);
      next();
    });
    
  • Query to get a key-value.

    function selectById(next) {
        console.log("\Getting by id");
        var query = 'SELECT * FROM uprofile.user where user_id=1';
        client.execute(query, { prepare: true}, function (err, result) {
        if (err) return next(err);
            result.rows.forEach(function(row) {
            console.log('Obtained row: %d | %s | %s ',row.user_id, row.user_name, row.user_bcity);
        }, this);
        next();
        });
    }
    

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app. The connection string enables your app to communicate with your hosted database.

  1. In the Azure portal, select Connection String.

    Use the Copy button button on the right side of the screen to copy the top value, the CONTACT POINT.

    View and copy the CONTACT POINT, USERNAME,and PASSWORD from the Azure portal, connection string page

  2. Open the config.js file.

  3. Paste the CONTACT POINT value from the portal over <FillMEIN> on line 4.

    Line 4 should now look similar to

    config.contactPoint = "cosmos-db-quickstarts.cassandra.cosmosdb.azure.com:10350"

  4. Copy the USERNAME value from the portal and paste it over <FillMEIN> on line 2.

    Line 2 should now look similar to

    config.username = 'cosmos-db-quickstart';

  5. Copy the PASSWORD value from the portal and paste it over <FillMEIN> on line 3.

    Line 3 should now look similar to

    config.password = '2Ggkr662ifxz2Mg==';

  6. Save the config.js file.

Use the X509 certificate

  1. Download the Baltimore CyberTrust Root certificate locally from https://cacert.omniroot.com/bc2025.crt. Rename the file using the file extension .cer.

    The certificate has serial number 02:00:00:b9 and SHA1 fingerprint d4🇩🇪20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74.

  2. Open uprofile.js and change the path\to\cert to point to your new certificate.

  3. Save uprofile.js.

Run the Node.js app

  1. In the git terminal window, run npm install to install the required npm modules.

  2. Run node uprofile.js to start your node application.

  3. Verify the results as expected from the command line.

    View and verify the output

    Press CTRL + C to stop execution of the program and close the console window.

  4. In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    View the data in Data Explorer

Review SLAs in the Azure portal

The throughput, storage, availability, latency, and consistency of the resources in your account are monitored in the Azure portal. Let's take a quick look at these metrics.

  1. Click Metrics in the navigation menu.

    Metrics in the Azure portal

  2. Click through each of the tabs so you're aware of the metrics Azure Cosmos DB provides.

    Each chart that's associated with the Azure Cosmos DB Service Level Agreements (SLAs) provides a line that shows if any of the SLAs have been violated. Azure Cosmos DB makes monitoring your SLAs transparent with this suite of metrics.

    Azure Cosmos DB metrics suite

Clean up resources

If you're not going to continue to use this app, delete all resources created by this quickstart with the following steps so you don't incur any charges:

  1. In the Azure portal, select Resource groups on the far left, and then select the resource group you created.

    If the left menu is collapsed, click Expand button to expand it.

    Metrics in the Azure portal

  2. In the new window select the resource group, and then click Delete resource group.

    Metrics in the Azure portal

  3. In the new window, type the name of the resource group to delete, and then click Delete.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a container using the Data Explorer, and run an app. You can now import additional data to your Cosmos DB account.