Posted on June 10, 2023
Working with Azure Cosmos DB in your Azure Functions Azure Cosmos DB is a powerful and scalable database service provided by Microsoft Azure. It is designed to handle globally distributed data to handle large-scale, high-performance applications that require low latency. Cosmos DB is a NoSQL database supporting multiple data models, documents, key-value, graphs, and tabular storage. With Cosmos DB, you can store and retrieve data using a variety of APIs, including SQL (Document DB), MongoDB, Cassandra, Gremlin, and Azure Table Storage. This flexibility allows you to work with Cosmos DB using familiar programming models and tools. It also offers features like automatic indexing, automatic secondary indexing, and built-in geospatial and temporal data support. Geospatial data can include various types of information, such as coordinates, elevation, demographics, land use, transportation networks, weather patterns, and more. Download and Install Azure Cosmos DB Emulator: Start the Azure Cosmos DB Emulator: Access the Azure Cosmos DB Emulator Explorer: Connect to the Emulator from your application: Note: These connection details are specific to the Azure Cosmos DB Emulator and should not be used in production. Insert Record Function: Change Feed Function: Relationship between the functions: The full source code for this article can be found on GitHub. The code handles the HTTP POST request, deserializes the request body into a StudentEntity object, creates a document with the student data, and returns the document as the response. It also performs error handling and logging using the provided ILogger instance. Note that you need to replace the values for databaseName, collectionName, and ConnectionStringSetting with your specific Cosmos DB configuration. Change Feed functions are useful for scenarios where you need to react to changes in your Cosmos DB data. It allows you to process and react to changes in real-time, enabling scenarios like data synchronization, notifications, analytics, or data transformations. By leveraging the Change Feed feature and an Azure Function, you can build event-driven architectures and automate workflows based on changes in your Cosmos DB data. In summary, By combining the Insert Record function and the Change Feed function, you can achieve a workflow where new records are inserted into Cosmos DB, and you can react to those insertions or changes in real-time using the Change Feed function. This allows for more dynamic and event-driven data processing and automation based on the changes happening in your Cosmos DB collection.What is Cosmos DB
Setup Cosmos in locally (Windows)
Setup Cosmos in Azure
Create Database & Container
Add Records Manually in Container
Students
database and the Items container.Save
.Let's create something real time.
Add Record Using HTTP Trigger Function
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace CodeHackCosmosTriggerFunctionApp
{
public static class InsertRecordFunction
{
[FunctionName("InsertRecord")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "records")] HttpRequest req,
[CosmosDB(
databaseName: "SchoolDB",
collectionName: "Students",
ConnectionStringSetting = "CosmosDBConnection")] out StudentEntity document, ILogger log)
{
document = null;
try
{
log.LogInformation("InsertRecord function processed a request.");
string requestBody = req.ReadAsStringAsync().Result;
var student = Newtonsoft.Json.JsonConvert.DeserializeObject<StudentEntity>(requestBody);
var jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var result = JsonConvert.SerializeObject(student, jsonSettings);
// Create a new document object with the record data
document = new StudentEntity
{
FirstName = student.FirstName,
LastName = student.LastName,
Email = student.Email,
PhoneNumber = student.PhoneNumber
};
}
catch (System.Exception ex)
{
log.LogError(ex.Message);
}
// Return a successful response with the inserted document
return new OkObjectResult(document);
}
}
public class StudentEntity
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("phoneNumber")]
public string PhoneNumber { get; set; }
}
}
Cosmos Trigger Function to track changes in a Cosmos DB Collection
public static class ChangeFeedFunction
{
[FunctionName("ChangeFeed")]
public static void Run([CosmosDBTrigger(
databaseName: "SchoolDB",
collectionName: "Students",
ConnectionStringSetting = "CosmosDBConnection",
CreateLeaseCollectionIfNotExists = true
)]IReadOnlyList<Document> input, ILogger log)
{
if (input != null && input.Count > 0)
{
log.LogInformation("Documents modified " + input.Count);
log.LogInformation("First document Id " + input[0].Id);
}
}
}
Summary with Output