Azure Cosmos DB: Build a Node.js application by using Graph API

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

This quick start demonstrates how to create an Azure Cosmos DB Graph API account, database, and graph using the Azure portal. You then build and run a console app by using the open-source Gremlin Node.js driver.

Prerequisites

Before you can run this sample, you must have the following prerequisites:

If you don't have an Azure subscription, create a free account before you begin.

Create a database account

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

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

    Azure portal "Databases" pane

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

    Setting Suggested value Description
    ID Enter a unique name Enter a unique name to identify this Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique but identifiable ID.

    The ID can contain only lowercase letters, numbers, and the hyphen (-) character, and it must contain 3 to 50 characters.
    API Gremlin (graph) The API determines the type of account to create. Azure Cosmos DB provides five APIs to suits the needs of your application: SQL (document database), Gremlin (graph database), MongoDB (document database), Azure Table, and Cassandra, each which currently require a separate account.

    Select Gremlin (graph) because in this quickstart you are creating a graph that is queryable using Gremlin syntax.

    Learn more about the Graph API
    Subscription Your subscription Select 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 above in ID
    Select Create New, then enter a new resource-group name for your account. For simplicity, you can use the same name as your ID.
    Location Select the region closest to your users Select geographic location in which 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.
    Enable geo-redundancy Leave blank This creates a replicated version of your database in a second (paired) region. Leave this blank.
    Pin to dashboard Select Select this box so that your new database account is added to your portal dashboard for easy access.

    Then click Create.

    The new account blade for Azure Cosmos DB

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

    The Azure portal Notifications pane

Add a graph

You can now use the Data Explorer tool in the Azure portal to create a graph database.

  1. Click Data Explorer > New Graph.

    The Add Graph area is displayed on the far right, you may need to scroll right to see it.

    The Azure portal Data Explorer, Add Graph page

  2. In the Add graph page, enter the settings for the new graph.

    Setting Suggested value Description
    Database ID sample-database Enter sample-database as the name for the new database. Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    Graph ID sample-graph Enter sample-graph as the name for your new collection. Graph names have the same character requirements as database IDs.
    Storage Capacity Fixed (10 GB) Leave the default value of Fixed (10 GB). This value is the storage capacity of the database.
    Throughput 400 RUs Change the throughput to 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later.
  3. Once the form is filled out, click OK.

Clone the sample application

Now let's clone a Graph API app from GitHub, set the connection string, and run it. You'll 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, and 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-graph-nodejs-getting-started.git
    
  4. Open the solution file in Visual Studio.

Review the code

This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to Update your connection string.

The following snippets are all taken from the app.js file.

  • The Gremlin client is created.

    const client = Gremlin.createClient(
        443, 
        config.endpoint, 
        { 
            "session": false, 
            "ssl": true, 
            "user": `/dbs/${config.database}/colls/${config.collection}`,
            "password": config.primaryKey
        });
    

    The configurations are all in config.js, which we edit in the following section.

  • A series of functions are defined to execute different Gremlin operations. This is one of them:

    function addVertex1(callback)
    {
        console.log('Running Add Vertex1'); 
        client.execute("g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44).property('userid', 1)", { }, (err, results) => {
          if (err) callback(console.error(err));
          console.log("Result: %s\n", JSON.stringify(results));
          callback(null)
        });
    }
    
  • Each function executes a client.execute method with a Gremlin query string parameter. Here is an example of how g.V().count() is executed:

    console.log('Running Count'); 
    client.execute("g.V().count()", { }, (err, results) => {
        if (err) return console.error(err);
        console.log(JSON.stringify(results));
        console.log();
    });
    
  • At the end of the file, all methods are then invoked using the async.waterfall() method. This will execute them one after the other:

    try{
        async.waterfall([
            dropGraph,
            addVertex1,
            addVertex2,
            addEdge,
            countVertices
            ], finish);
    } catch(err) {
        console.log(err)
    }
    

Update your connection string

  1. Open the config.js file.

  2. In config.js, fill in the config.endpoint key with the Gremlin URI value from the Overview page of the Azure portal.

    config.endpoint = "GRAPHENDPOINT";

    View and copy an access key in the Azure portal, Keys blade

    If the Gremlin URI value is blank, you can generate the value from the Keys page in the portal. Use the URI value, remove https://, and change documents to gremlin.cosmosdb. If your graph account was created before December 20th, 2017, change documents to graphs.

    The Gremlin endpoint must be only the host name without the protocol/port number, like mygraphdb.gremlin.cosmosdb.azure.com (not https://mygraphdb.gremlin.cosmosdb.azure.com or mygraphdb.gremlin.cosmosdb.azure.com:433).

  3. In config.js, fill in the config.primaryKey value with the Primary Key value from the Keys page of the Azure portal.

    config.primaryKey = "PRIMARYKEY";

    Azure portal "Keys" blade

  4. Enter the database name, and graph (container) name for the value of config.database and config.collection.

Here's an example of what your completed config.js file should look like:

var config = {}

// Note that this must not have HTTPS or the port number
config.endpoint = "testgraphacct.gremlin.cosmosdb.azure.com";
config.primaryKey = "Pams6e7LEUS7LJ2Qk0fjZf3eGo65JdMWHmyn65i52w8ozPX2oxY3iP0yu05t9v1WymAHNcMwPIqNAEv3XDFsEg==";
config.database = "graphdb"
config.collection = "Persons"

module.exports = config;

Run the console app

  1. Open a terminal window and change (via cd command) to the installation directory for the package.json file that's included in the project.

  2. Run npm install to install the required npm modules, including gremlin.

  3. Run node app.js in a terminal to start your node application.

Browse with Data Explorer

You can now go back to Data Explorer in the Azure portal to view, query, modify, and work with your new graph data.

In Data Explorer, the new database appears in the Graphs pane. Expand the database, followed by the container, and then select Graph.

The data generated by the sample app is displayed in the next pane within the Graph tab when you select Apply Filter.

Try completing g.V() with .has('firstName', 'Thomas') to test the filter. Note that the value is case sensitive.

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 your 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 article, you learned how to create an Azure Cosmos DB account, create a graph by using Data Explorer, and run an app. You can now build more complex queries and implement powerful graph traversal logic by using Gremlin.