0% found this document useful (0 votes)
118 views4 pages

Fetch Data From Azure Cosmos DB

This document provides steps to fetch data from Azure Cosmos DB using C#: Step 1 is to install the NuGet package. Step 2 is to connect to an Azure Cosmos DB account by adding namespaces and global variables containing the endpoint URI and primary key. The code then creates a DocumentClient instance and executes a query against a specified database and collection to retrieve family data. It demonstrates running the same query with LINQ and direct SQL, and provides REST API and code sample links for additional querying options including streaming data to Cosmos DB from IoT Hub or creating an Azure function triggered by Cosmos DB changes.

Uploaded by

Priti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views4 pages

Fetch Data From Azure Cosmos DB

This document provides steps to fetch data from Azure Cosmos DB using C#: Step 1 is to install the NuGet package. Step 2 is to connect to an Azure Cosmos DB account by adding namespaces and global variables containing the endpoint URI and primary key. The code then creates a DocumentClient instance and executes a query against a specified database and collection to retrieve family data. It demonstrates running the same query with LINQ and direct SQL, and provides REST API and code sample links for additional querying options including streaming data to Cosmos DB from IoT Hub or creating an Azure function triggered by Cosmos DB changes.

Uploaded by

Priti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Fetch data from Azure Cosmos DB using C#

Step 1: Install Nuget package.

Step 2: Connect to an Azure Cosmos DB account

Add these namespaces to your code

// ADD THIS PART TO YOUR CODE

using System.Net;

using Microsoft.Azure.Documents;

using Microsoft.Azure.Documents.Client;

using Newtonsoft.Json;

Add these global variable in your code file.


private static readonly string EndpointUri = "https://test.documents.azure.com:443/";

/// <summary>
/// The primary key for the Azure DocumentDB account.
/// </summary>
private static readonly string PrimaryKey = "<primary key>";

/// <summary>
/// The DocumentDB client instance.
/// </summary>6n6yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
private DocumentClient client;

Add below code in main function-Here I am just execute select command from cosmosdb
collection
// Create a new instance of the DocumentClient
this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

this.ExecutefetchQuery("FamilyDB_og", "FamilyCollection_og");

private void ExecuteFetchQuery(string databaseName, string collectionName)


{
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };

// Run a simple query via LINQ. DocumentDB indexes all properties, so


queries can be completed efficiently and with low latency.
// Here we find the Andersen family via its LastName
IQueryable<Family> familyQuery = this.client.CreateDocumentQuery<Family>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
queryOptions)
.Where(f => f.LastName == "Andersen");

// The query is executed synchronously here, but can also be executed


asynchronously via the IDocumentQuery<T> interface
Console.WriteLine("Running LINQ query...");
foreach (Family family in familyQuery)
{
Console.WriteLine("\tRead {0}", family);
}

// Now execute the same query via direct SQL


IQueryable<Family> familyQueryInSql =
this.client.CreateDocumentQuery<Family>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
"SELECT * FROM Family WHERE Family.LastName = 'Andersen'",
queryOptions);

Console.WriteLine("Running direct SQL query...");


foreach (Family family in familyQueryInSql)
{
Console.WriteLine("\tRead {0}", family);
}

Console.WriteLine("Press any key to continue ...");


Console.ReadKey();
}
Using REST query Azure Cosmos DB

verb="POST";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs",
databaseId, collectionId);
resourceId = (idBased) ? string.Format("dbs/{0}/colls/{1}",
databaseId, collectionId) : collectionId.ToLowerInvariant();

authHeader = GenerateMasterKeyAuthorizationSignature(verb,
resourceId, resourceType, masterKey, "master", "1.0");

client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization",
authHeader);
client.DefaultRequestHeaders.Add("x-ms-documentdb-isquery",
"True");

var qry = new SqlQuerySpec { query = "SELECT * FROM root" };


var r = client.PostWithNoCharSetAsync(new Uri(baseUri,
resourceLink), qry).Result;

Console.WriteLine(r.Content.ToString());

API-

https://docs.microsoft.com/en-us/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-
rest-api

https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/rest-from-
.net/Program.cs

For API calling need parameter like

databaseId, collectionId, masterKey and baseurl

Strrim real time data to Azure cosmos db- https://www.striim.com/striim-for-azure-cosmos-db/

https://medium.com/@avirup171/azure-iot-hub-azure-function-azure-cosmos-db-walkthrough-
cc30d12d1055
Create a azure function that will be trigger by Azure Cosmos DB

https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-cosmos-db-triggered-
function

You might also like