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 article demonstrates how to create an Azure Cosmos DB account for Graph API (preview), database, and graph by 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 window, sign in to the Azure portal.

  2. In the left pane, select New > Databases > Azure Cosmos DB > Create.

    Azure portal "Databases" pane

  3. Under New account, specify the configuration that you want for this Azure Cosmos DB account.

    With Azure Cosmos DB, you can choose one of four programming models: Gremlin (graph), MongoDB, SQL (DocumentDB), and Table (key-value). Each model currently requires a separate account.

    In this Quick Start article, we program against the Graph API, so choose Gremlin (graph) as you fill out the form. If you have document data from a catalog app, key/value (table) data, or data that's migrated from a MongoDB app, realize that Azure Cosmos DB can provide a highly available, globally distributed database service platform for all your mission-critical applications.

    Fill in the fields on the New account blade by using the information in the following screenshot as a guide. Your values might be different from the values in the screenshot.

    "New account" blade

    Setting Suggested value Description
    ID Unique value A unique name that identifies 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 must contain only lowercase letters, numbers, and the hyphen (-) character. It must contain from 3 to 50 characters.
    API Gremlin (graph) We program against the Graph API later in this article.
    Subscription Your subscription The Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource group The same value as ID The new resource group name for your account. For simplicity, you can use the same name as your ID.
    Location The region closest to your users The geographic location in which to host your Azure Cosmos DB account. Choose the location closest to your users to give them the fastest access to the data.
  4. Select Create to create the account.

  5. On the toolbar, select the Notifications icon Notifications icon to monitor the deployment process.

    Azure portal "Notifications" pane

  6. When the Notifications window indicates the deployment succeeded, close the window. Open the new account from the All resources tile on the Dashboard.

    "All resources" tile

Add a graph

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

  1. In the Azure portal, in the menu on the left, select Data Explorer (Preview).

  2. Under Data Explorer (Preview), select New Graph. Then fill in the page by using the following information:

    Data Explorer in the Azure portal

    Setting Suggested value Description
    Database id sample-database The ID for your new database. Database names must be between 1 and 255 characters and can't contain / \ # ? or a trailing space.
    Graph id sample-graph The ID for your new graph. Graph names have the same character requirements as database IDs.
    Storage capacity 10 GB Leave the default value. This is the storage capacity of the database.
    Throughput 400 RUs Leave the default value. You can scale up the throughput later if you want to reduce latency.
    Partition key /userid A partition key that distributes data evenly to each partition. Selecting the correct partition key is important in creating a performant graph. For more information, see Designing for partitioning.
  3. After the form is filled out, select 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 Git terminal window, such as Git Bash, and change (via cd command) to a working directory.

  2. Run the following command to clone the sample repository:

    git clone https://github.com/Azure-Samples/azure-cosmos-db-graph-nodejs-getting-started.git
    
  3. Open the solution file in Visual Studio.

Review the code

Let's make a quick review of what's happening in the app. Open the app.js file, and you see the following lines of code.

  • 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 Gremlin steps are executed with the client.execute method.

    console.log('Running Count'); 
    client.execute("g.V().count()", { }, (err, results) => {
        if (err) return console.error(err);
        console.log(JSON.stringify(results));
        console.log();
    });
    

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 graphs.

    The Gremlin endpoint must be only the host name without the protocol/port number, like mygraphdb.graphs.azure.com (not https://mygraphdb.graphs.azure.com or mygraphdb.graphs.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.graphs.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 collection, 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

Now that your app is up and running, you'll want to ensure business continuity and watch user access to ensure high availability. You can use the Azure portal to review the availability, latency, throughput, and consistency of your collection.

Each graph that's associated with the Azure Cosmos DB Service Level Agreements (SLAs) provides a line that shows the quota required to meet the SLA and your actual usage. This information gives you a clear view into your database performance. Additional metrics, such as storage usage and number of requests per minute, are also included in the portal.

  • In the Azure portal, in the pane on the left, under Monitoring, select Metrics.

    Todo app with sample data

Clean up your resources

If you do not plan to continue using this app, delete all resources that you created in this article by doing the following:

  1. In the Azure portal, on the left navigation menu, select Resource groups. Then select the name of the resource that you created.

  2. On your resource group page, select Delete. Type the name of the resource to be deleted, and then select 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.