Connect to and query an Azure NoSQL graph database
   4 min read

Prerequisites

Connect to and query an Azure NoSQL graph database

You can use C# to connect to and create a graph in your Azure NoSQL database.

C# code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Linq;
using System.Net.WebSockets;
using System.Text.Json;
using Gremlin.Net.Driver;
using Gremlin.Net.Structure.IO.GraphSON;
using Newtonsoft.Json;

namespace GremlinNetSample
{
    // based on Azure sample: https://github.com/Azure-Samples/azure-cosmos-db-graph-gremlindotnet-getting-started
    class Program
    {
        static void Main(string[] args)
        {
            // Azure Cosmos Graph database configuration values:
            var host = "mycosmos-account.gremlin.cosmos.azure.com";
            var port = 443;
            var enableSsl = true;
            var databaseName = "mydatabase";
            var graphName = "mygraph";
            var username = $"/dbs/{databaseName}/colls/{graphName}";
            var password = Environment.GetEnvironmentVariable("GREMLIN_DB_PRIMARY_KEY");   // store primary key as a system environment variable.

            // create a gremlin server object:
            var gremlinServer = new GremlinServer(host, port, enableSsl, username, password);

            // configure connection pool:
            var connectionPoolSettings = new ConnectionPoolSettings()
            {
                MaxInProcessPerConnection = 10,
                PoolSize = 30,
                ReconnectionAttempts = 3,
                ReconnectionBaseDelay = TimeSpan.FromMilliseconds(500)
            };

            // create a websocket configuration object:
            var webSocketConfiguration =
                new Action<ClientWebSocketOptions>(options =>
                {
                    options.KeepAliveInterval = TimeSpan.FromSeconds(10);
                });

            // create a gremlin client:
            using var gremlinClient = new GremlinClient(
                gremlinServer,
                new GraphSON2Reader(),
                new GraphSON2Writer(),
                GremlinClient.GraphSON2MimeType,
                connectionPoolSettings,
                webSocketConfiguration);

            RunQueries(gremlinClient);
        }

        // Run your queries here.
        private static void RunQueries(GremlinClient gremlinClient)
        {
            string myQuery = null;

            // delete all graph vertices, edges, and properties (does not delete the graph):
            myQuery = "g.V().drop()";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a person):
            myQuery = "g.addV('person').property('id', 'Juanita').property('firstName', 'Juanita').property('location', 'Los Angeles').property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a person):
            myQuery = "g.addV('person').property('id', 'Sam').property('firstName', 'Sam').property('location', 'New Mexico').property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a person):
            myQuery = "g.addV('person').property('id', 'Nikhil').property('firstName', 'Nikhil').property('location', 'New York').property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a movie):
            myQuery = "g.addv('movie').property('id', 'I, robot').property('title', 'I, robot').property('year', 2004).property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a movie):
            myQuery = "g.addv('movie').property('id', 'Fried green tomatoes').property('title', 'Fried green tomatoes').property('year', 1991).property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add vertex (a movie):
            myQuery = "g.addv('movie').property('id', 'David Copperfield').property('title', 'David Copperfield').property('year', 2019).property('pk', 'pk')";
            SendQuery(gremlinClient, myQuery);

            // add edge (a relationship):
            myQuery = "g.V('Juanita').addE('knows').to(g.V('Sam'))";
            SendQuery(gremlinClient, myQuery);

            // add edge (a relationship):
            myQuery = "g.V('Sam').addE('knows').to(g.V('Nikhil'))";
            SendQuery(gremlinClient, myQuery);

            // add edge (a relationship):
            myQuery = "g.V('Juanita').addE('likes').to(g.V('I, robot'))";
            SendQuery(gremlinClient, myQuery);

            // add edge (a relationship):
            myQuery = "g.V('Sam').addE('likes').to(g.V('Fried green tomatoes'))";
            SendQuery(gremlinClient, myQuery);

            // add edge (a relationship):
            myQuery = "g.V('Nikhil').addE('likes').to(g.V('David Copperfield'))";
            SendQuery(gremlinClient, myQuery);

            // count vertices:
            myQuery = "g.V().count()";
            SendQuery(gremlinClient, myQuery);

            // get graph contents:
            myQuery = "g.V()";
            SendQuery(gremlinClient, myQuery);

            // get the person that Juanita knows (Person A):
            myQuery = "g.V('Juanita').out('knows').hasLabel('person')";
            SendQuery(gremlinClient, myQuery);

            // get the movie that Person A likes:
            myQuery = "g.V('Juanita').out('knows').hasLabel('person').out('likes')";
            SendQuery(gremlinClient, myQuery);

            // get the person that Person A knows (Person B):
            myQuery = "g.V('Juanita').out('knows').hasLabel('person').out('knows').hasLabel('person')";
            SendQuery(gremlinClient, myQuery);

            // get the movie that Person B likes:
            myQuery = "g.V('Juanita').out('knows').hasLabel('person').out('knows').hasLabel('person').out('likes')";
            SendQuery(gremlinClient, myQuery);
        }

        // send gremlin query to cloud for execution and print result.
        private static void SendQuery(GremlinClient gremlinClient, string query)
        {
            try
            {
                var resultSet = gremlinClient.SubmitAsync<dynamic>(query).Result;
                
                Console.WriteLine(Environment.NewLine + $"Result set for query: {query}");
                var jsonStr = "[" + string.Join(",", resultSet.Select(x => JsonConvert.SerializeObject(x))) + "]";
                PrettyPrintJson(jsonStr);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // prettyprint JSON string.
        public static void PrettyPrintJson(string jsonString)
        {
            var options = new JsonSerializerOptions()
            {
                WriteIndented = true
            };

            var jsonElement = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(jsonString);

            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(jsonElement, options));
        }
    }
}

Microsoft Azure Data Explorer

You can use the Microsoft Azure Data Explorer to view and query your graph database:

  1. Sign into your Microsoft Azure account.

  2. Search for your database in Recent resources or choose Azure Cosmos DB, and then select View:

    Screenshot of &lsquo;Azure Cosmos DB&rsquo; button.


  3. Choose Data Explorer. In the right hand pane, expand the Data node to see your graph database:

    Screenshot of &lsquo;Data Explorer&rsquo; button.


  4. Expand the Scale node for your graph database, choose Graph, and then select the Load graph button:

    Screenshot of &lsquo;Load graph&rsquo; button.


  5. In the Results list, choose a vertex to see its associated edges and vertices in your graph, with its properties listed to the right:

    Screenshot of &lsquo;Results&rsquo; page.


Notes

Azure NoSQL graph database does not support the SPARQL query language.

Next steps