Azure Cosmos DB: Build a .NET Framework or Core application using the Graph API

Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. 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 account, database, and graph (container) using the Azure portal. You then build and run a console app built using the open-source driver Gremlin.Net.


If you don’t already have Visual Studio 2017 installed, you can download and use the free Visual Studio 2017 Community Edition. Make sure that you enable Azure development during the Visual Studio setup.

If you already have Visual Studio 2017 installed, make sure to be installed up to Visual Studio 2017 Update 3.

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 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 Enter the same unique name as provided above in ID 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. During account creation the portal displays the Deploying Azure Cosmos DB tile on the right side, you may need to scroll right on your dashboard to see the tile. There is also a progress bar displayed near the top of the screen. You can watch either area for progress.

    The Azure portal Notifications pane

    Once the account is created, the Congratulations! Your Azure Cosmos DB account was created page is displayed.

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 Enter sample-database as the name for the new database. Database names must be between 1 and 255 characters and can't 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 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.
  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 cd to your working directory.

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

    git clone
  3. Then open Visual Studio and open the solution file.

  4. Restore the NuGet packages in the project. This should include the Gremlin.Net driver, as well as the Newtonsoft.Json package.

  5. You can also install the Gremlin.Net driver manually, version 3.2.7, using the Nuget package manager, or the nuget command-line utility:

    nuget install Gremlin.Net -Version 3.2.7

Review the code

Let's make a quick review of what's happening in the app. Open the Program.cs file and you'll find that these lines of code create the Azure Cosmos DB resources.

  • Set your connection parameters based on the account created above (Line 19):

    private static string hostname = "";
    private static int port = 443;
    private static string authKey = "your-authentication-key";
    private static string database = "your-database";
    private static string collection = "your-collection-or-graph";
  • The Gremlin commands to be executed are listed in a Dictionary (Line 26):

    private static Dictionary<string, string> gremlinQueries = new Dictionary<string, string>
        { "Cleanup",        "g.V().drop()" },
        { "AddVertex 1",    "g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44)" },
        { "AddVertex 2",    "g.addV('person').property('id', 'mary').property('firstName', 'Mary').property('lastName', 'Andersen').property('age', 39)" },
        { "AddVertex 3",    "g.addV('person').property('id', 'ben').property('firstName', 'Ben').property('lastName', 'Miller')" },
        { "AddVertex 4",    "g.addV('person').property('id', 'robin').property('firstName', 'Robin').property('lastName', 'Wakefield')" },
        { "AddEdge 1",      "g.V('thomas').addE('knows').to(g.V('mary'))" },
        { "AddEdge 2",      "g.V('thomas').addE('knows').to(g.V('ben'))" },
        { "AddEdge 3",      "g.V('ben').addE('knows').to(g.V('robin'))" },
        { "UpdateVertex",   "g.V('thomas').property('age', 44)" },
        { "CountVertices",  "g.V().count()" },
        { "Filter Range",   "g.V().hasLabel('person').has('age', gt(40))" },
        { "Project",        "g.V().hasLabel('person').values('firstName')" },
        { "Sort",           "g.V().hasLabel('person').order().by('firstName', decr)" },
        { "Traverse",       "g.V('thomas').out('knows').hasLabel('person')" },
        { "Traverse 2x",    "g.V('thomas').out('knows').hasLabel('person').out('knows').hasLabel('person')" },
        { "Loop",           "g.V('thomas').repeat(out()).until(has('id', 'robin')).path()" },
        { "DropEdge",       "g.V('thomas').outE('knows').where(inV().has('id', 'mary')).drop()" },
        { "CountEdges",     "g.E().count()" },
        { "DropVertex",     "g.V('thomas').drop()" },
  • Create a GremlinServer connection object using the parameters provided above (Line 52):

    var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, 
                                                    username: "/dbs/" + database + "/colls/" + collection, 
                                                    password: authKey);
  • Create a new GremlinClient object (Line 56):

    var gremlinClient = new GremlinClient(gremlinServer);
  • Execute each Gremlin query using the GremlinClient object with an async task (Line 63). This will read the Gremlin queries from the dictionary defined above (Line 26):

    var task = gremlinClient.SubmitAsync<dynamic>(query.Value);
  • Retrieve the result and read the values, which are formatted as a dictionary, using the JsonSerializer class from Newtonsoft.Json:

    foreach (var result in task.Result)
        // The vertex results are formed as dictionaries with a nested dictionary for their properties
        string output = JsonConvert.SerializeObject(result);
        Console.WriteLine(String.Format("\tResult:\n\t{0}", output));

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. In the Azure portal, click Keys.

    Copy the first portion of the URI value.

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

  2. In Program.cs paste the value over your-endpoint in the hostname variable in line 19.

    "private static string hostname = "";

    The endpoint value should now look like this:

    "private static string hostname = "";

  3. Copy your PRIMARY KEY value from the portal, and paste it in the authkey variable, replacing the "your-authentication-key" placeholder in line 21.

    private static string authKey = "your-authentication-key";

  4. Using the information of the database created above, paste the database name inside of the database variable in line 22.

    private static string database = "your-database";

  5. Similarly, using the information of the collection created above, paste the collection (which is also the graph name) inside of the collection variable in line 23.

    private static string collection = "your-collection-or-graph";

  6. Save the Program.cs file.

You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

Run the console app

Click CTRL + F5 to run the application. The application will print both the Gremlin query commands and results in the console.

The console window displays the vertexes and edges being added to the graph. When the script completes, press ENTER to close the console window.

Browse using the Data Explorer

You can now go back to Data Explorer in the Azure portal and browse and query your new graph data.

  1. In Data Explorer, the new database appears in the Graphs pane. Expand the database and collection nodes, and then click Graph.

  2. Click the Apply Filter button to use the default query to view all the vertices in the graph. The data generated by the sample app is displayed in the Graphs pane.

    You can zoom in and out of the graph, you can expand the graph display space, add additional vertices, and move vertices on the display surface.

    View the graph in Data Explorer in the Azure portal

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 in the Azure portal with the following steps:

  1. From the left-hand menu in the Azure portal, click Resource groups and then click the name of the resource you created.
  2. On your resource group page, click Delete, type the name of the resource to delete in the text box, and then click Delete.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a graph using the Data Explorer, and run an app. You can now build more complex queries and implement powerful graph traversal logic using Gremlin.