Calling Azure Cosmos DB Graph API from Azure Functions

Azure Functions at this time provides Input and output Bindings for DocumentDB, one of the Database Models in Azure Cosmos DB. There aren't any for Cosmos DB Graph yet. However, using the ability to reference external assemblies and importing them through NuGet Packages, it is possible to access these APIs from the C# Scripts in Azure Functions.

 1) Create a Graph Container in CosmosDB

I have used the starter Solution available in the Documentation for Azure Cosmos DB, that showcases how to use .NET Code to create a Cosmos DB Database, a Graph Container in it, and inject data using the Graph API into this container. It also shows how to query the Graph using the APIs. Once this Starter Solution is deployed, you could use the built in Graph Explorer to traverse the Graph and view the Nodes and Vertices.

 2) Create an Azure Function App

Create an Azure Function App, add a Function in it; use the HTTPTrigger Template in it if this Function ought to be invoked from a Client Application. For this exercise, I have used a TimerTrigger Template in C#.

 3) Reference external assemblies in project.json and upload this file to the Function App Deployment folder

The project.json that I used and the assemblies that had to be referenced were:

{
"frameworks": {
"net46": {
"dependencies": {
"Microsoft.Azure.DocumentDB": "1.14.0",
"Microsoft.Azure.Graphs": "0.2.2-preview",
"Newtonsoft.Json": "6.0.8",
"System.Collections": "4.0.0",
"System.Collections.Immutable": "1.1.37",
"System.Globalization": "4.0.0",
"System.Linq": "4.0.0",
"System.Threading" :  "4.0.0"
}
}
}
}

The project.json file needs to be uploaded to the location https://<function_app_name>.scm.azurewebsites.net. The Azure Documentation here  and here outlines the steps required to be performed.  See screenshot below:

 

4) Add environmental variables to the App Settings of the Function App

This is to store the Graph Connection information in the environment variables of the Function App

5) Adding the C# Scripts in the Azure Function that calls the Graph API

I have repurposed the code from the Starter sample referred earlier in this article, made minimal changes to suit this article. The Gremlin query used here sorts all the Persons (Nodes) in the Graph, sorted descending on their First Names

Trigger this function and view the results from the execution of the Gremlin Query, in the execution log