Processing Azure Cosmos DB Change Feed with Azure Functions
    • Dark
      Light
    • PDF

    Processing Azure Cosmos DB Change Feed with Azure Functions

    • Dark
      Light
    • PDF

    Article Summary

    #ServerlessTips - Azure Functions
    Author: Rahul Rai Microsoft MVP

    Azure Cosmos DB is the most popular NoSQL database used by many new generation applications. Azure Cosmos DB change feed enables you to get a continuous and incremental feed of records from an Azure Cosmos container as the records in it are created and modified.

    In this article, we will learn to use Azure Functions to process the change feed from a container in the Azure Cosmos DB.

    Setup

    Use the instructions on the Microsoft docs website to create a new Cosmos DB account, and a container named employee in a database named mycompany as follows:
    Picture122

    Add a few records to the container with the help of the Data Explorer tool. Create a new function app in the same resource group using the following Azure CLI commands:

    az storage account create --name <storage account> --location eastus --resource-group <resource group> --sku "Standard_LRS"
    az functionapp create –name <function app> --storage-account <storage account> --consumption-plan-location "eastus" --resource-group <resource group> --functions-version 4 --os-type Windows
    
    

    After the Function App is ready, head back to the Cosmos DB account and click on the Add Azure Function option in the Integrations section. The selection will launch a panel where you can select your Function App and specify the name and the language of the Azure Function that listens to the change feed of the selected Cosmos DB container.
    Picture220

    Navigate to your function and replace the boilerplate code with the following:

    #r "Microsoft.Azure.DocumentDB.Core"
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    using System;
    public static async Task Run(IReadOnlyList<Document> input, ILogger log)
    {
        log.LogInformation("Document count " + input.Count);
        foreach (var item in input)
        {
            log.LogInformation("Document: " + item.ToString());
        }
    }
    
    

    Picture316

    Test

    Click on the Monitor option in the Function console and switch to the Logs tab, which will show you a terminal connected to the log streaming service. In another browser window, open the Data Explorer tool of Cosmos DB and update a document. You will see the change invoking the function soon after as follows:
    Picture414

    You can use change feeds to replicate containers, trigger API calls for an event-driven architecture, reformatting data, archive data to secondary data stores, etc.

    MicrosoftTeams-image 491


    Was this article helpful?