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 on the Graph API (preview).

Prerequisites

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 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 /firstName 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.

This sample project is using .NET Core project format and has been configured to target the following frameworks:

  • netcoreapp2.0
  • net461
  1. Open a git terminal window, such as git bash, and cd 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-dotnet-getting-started.git
    
  3. Then open Visual Studio and open the solution file.

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.

  • The DocumentClient is initialized. In the preview, we added a graph extension API on the Azure Cosmos DB client. We are working on a standalone graph client decoupled from the Azure Cosmos DB client and resources.

    using (DocumentClient client = new DocumentClient(
        new Uri(endpoint),
        authKey,
        new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp }))
    
  • A new database is created.

    Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "graphdb" });
    
  • A new graph is created.

    DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
        UriFactory.CreateDatabaseUri("graphdb"),
        new DocumentCollection { Id = "graph" },
        new RequestOptions { OfferThroughput = 1000 });
    
  • A series of Gremlin steps are executed using the CreateGremlinQuery method.

    // The CreateGremlinQuery method extensions allow you to execute Gremlin queries and iterate
    // results asychronously
    IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, "g.V().count()");
    while (query.HasMoreResults)
    {
        foreach (dynamic result in await query.ExecuteNextAsync())
        {
            Console.WriteLine($"\t {JsonConvert.SerializeObject(result)}");
        }
    }
    

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 Visual Studio 2017, open the appsettings.json file.

  2. In the Azure portal, in your Azure Cosmos DB account, click Keys in the left navigation.

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

  3. Copy your URI value from the portal and make it the value of the Endpoint key in appsettings.json. You can use the copy button as shown in the preceding screenshot to copy the value.

    "endpoint": "https://FILLME.documents.azure.com:443/",

  4. Copy your PRIMARY KEY value from the portal, and make it the value of the AuthKey key in App.config, then save your changes.

    "authkey": "FILLME"

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

Run the console app

Before running the application, it is recommended that you update the Microsoft.Azure.Graphs package to the latest version.

  1. In Visual Studio, right-click on the GraphGetStarted project in Solution Explorer and then click Manage NuGet Packages.

  2. In the NuGet Package Manager Updates tab, type Microsoft.Azure.Graphs and check the Includes prerelease box.

  3. From the results, update the Microsoft.Azure.Graphs library to the latest version of the package. This installs the Azure Cosmos DB graph extension library package and all dependencies.

    If you get a message about reviewing changes to the solution, click OK. If you get a message about license acceptance, click I accept.

  4. Click CTRL + F5 to run the application.

    The console window displays the vertexes and edges being added to the graph. When the script completes, press ENTER twice 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 graphdb, graphcollz, and then click Graph.

  2. Click the Apply Filter button to use the default query to view all the verticies 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 verticies, and move verticies on the display surface.

    View the graph in Data Explorer in the Azure portal

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