Skip to content

Files

397 lines (281 loc) · 16 KB

functions-bindings-cosmosdb-v2-trigger.md

File metadata and controls

397 lines (281 loc) · 16 KB
title description ms.topic ms.date ms.devlang ms.custom zone_pivot_groups
Azure Cosmos DB trigger for Functions 2.x and higher
Learn to use the Azure Cosmos DB trigger in Azure Functions.
reference
03/04/2022
csharp, java, javascript, powershell, python
devx-track-csharp, devx-track-python
programming-languages-set-functions-lang-workers

Azure Cosmos DB trigger for Azure Functions 2.x and higher

The Azure Cosmos DB Trigger uses the Azure Cosmos DB Change Feed to listen for inserts and updates across partitions. The change feed publishes inserts and updates, not deletions.

For information on setup and configuration details, see the overview.

Example

::: zone pivot="programming-language-csharp"

The usage of the trigger depends on the extension package version and the C# modality used in your function app, which can be one of the following:

An in-process class library is a compiled C# function runs in the same process as the Functions runtime.

An isolated process class library compiled C# function runs in a process isolated from the runtime. Isolated process is required to support C# functions running on .NET 5.0.

C# script is used primarily when creating C# functions in the Azure portal.


The following examples depend on the extension version for the given C# mode.

The following example shows a C# function that is invoked when there are inserts or updates in the specified database and collection.

using Microsoft.Azure.Documents;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "ToDoItems",
            collectionName: "Items",
            ConnectionStringSetting = "CosmosDBConnection",
            LeaseCollectionName = "leases",
            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents,
            ILogger log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.LogInformation($"Documents modified: {documents.Count}");
                log.LogInformation($"First document Id: {documents[0].Id}");
            }
        }
    }
}

Apps using Cosmos DB extension version 4.x or higher will have different attribute properties, which are shown below. This example refers to a simple ToDoItem type.

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}
using System.Collections.Generic;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class CosmosTrigger
    {
        [FunctionName("CosmosTrigger")]
        public static void Run([CosmosDBTrigger(
            databaseName: "databaseName",
            containerName: "containerName",
            Connection = "CosmosDBConnectionSetting",
            LeaseContainerName = "leases",
            CreateLeaseContainerIfNotExists = true)]IReadOnlyList<ToDoItem> input, ILogger log)
        {
            if (input != null && input.Count > 0)
            {
                log.LogInformation("Documents modified " + input.Count);
                log.LogInformation("First document Id " + input[0].Id);
            }
        }
    }
}

The following code defines a MyDocument type:

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/CosmosDB/CosmosDBFunction.cs" range="37-46":::

This document type is the type of the IReadOnlyList<T> used as the Cosmos DB trigger binding parameter in the following example:

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/CosmosDB/CosmosDBFunction.cs" range="4-35":::

Example pending.

The following example shows a Cosmos DB trigger binding in a function.json file and a C# script function that uses the binding. The function writes log messages when Cosmos DB records are added or modified.

Here's the binding data in the function.json file:

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "<connection-app-setting>",
    "databaseName": "Tasks",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": true
}

Here's the C# script code:

    #r "Microsoft.Azure.DocumentDB.Core"

    using System;
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    using Microsoft.Extensions.Logging;

    public static void Run(IReadOnlyList<Document> documents, ILogger log)
    {
      log.LogInformation("Documents modified " + documents.Count);
      log.LogInformation("First document Id " + documents[0].Id);
    }

The following example shows a Cosmos DB trigger binding in a function.json file and a C# script function that uses the binding. The function writes log messages when Cosmos DB records are added or modified.

Here's the binding data in the function.json file:

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseContainerName": "leases",
    "connection": "<connection-app-setting>",
    "databaseName": "Tasks",
    "containerName": "Items",
    "createLeaseContainerIfNotExists": true
}

Here's the C# script code:

    #r "Microsoft.Azure.DocumentDB.Core"

    using System;
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    using Microsoft.Extensions.Logging;

    public static void Run(IReadOnlyList<Document> documents, ILogger log)
    {
      log.LogInformation("Documents modified " + documents.Count);
      log.LogInformation("First document Id " + documents[0].Id);
    }

::: zone-end ::: zone pivot="programming-language-java"

This function is invoked when there are inserts or updates in the specified database and collection.

    @FunctionName("cosmosDBMonitor")
    public void cosmosDbProcessor(
        @CosmosDBTrigger(name = "items",
            databaseName = "ToDoList",
            collectionName = "Items",
            leaseCollectionName = "leases",
            createLeaseCollectionIfNotExists = true,
            connectionStringSetting = "AzureCosmosDBConnection") String[] items,
            final ExecutionContext context ) {
                context.getLogger().info(items.length + "item(s) is/are changed.");
            }

[!INCLUDE functions-cosmosdb-extension-java-note]


In the Java functions runtime library, use the @CosmosDBTrigger annotation on parameters whose value would come from Cosmos DB. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

::: zone-end
::: zone pivot="programming-language-javascript"

The following example shows a Cosmos DB trigger binding in a function.json file and a JavaScript function that uses the binding. The function writes log messages when Cosmos DB records are added or modified.

Here's the binding data in the function.json file:

[!INCLUDE functions-cosmosdb-trigger-attributes]

Here's the JavaScript code:

    module.exports = async function (context, documents) {
      context.log('First document Id modified : ', documents[0].id);
    }

::: zone-end
::: zone pivot="programming-language-powershell"

The following example shows how to run a function as data changes in Cosmos DB.

[!INCLUDE functions-cosmosdb-trigger-attributes]

In the run.ps1 file, you have access to the document that triggers the function via the $Documents parameter.

param($Documents, $TriggerMetadata) 

Write-Host "First document Id modified : $($Documents[0].id)" 

::: zone-end
::: zone pivot="programming-language-python"

The following example shows a Cosmos DB trigger binding in a function.json file and a Python function that uses the binding. The function writes log messages when Cosmos DB records are modified.

Here's the binding data in the function.json file:

[!INCLUDE functions-cosmosdb-trigger-attributes]

Here's the Python code:

    import logging
    import azure.functions as func


    def main(documents: func.DocumentList) -> str:
        if documents:
            logging.info('First document Id modified: %s', documents[0]['id'])

::: zone-end
::: zone pivot="programming-language-csharp"

Attributes

Both in-process and isolated process C# libraries use the CosmosDBTriggerAttribute to define the function. C# script instead uses a function.json configuration file.

[!INCLUDE functions-cosmosdb-attributes-v3]

[!INCLUDE functions-cosmosdb-attributes-v4]

[!INCLUDE functions-cosmosdb-attributes-v3]

[!INCLUDE functions-cosmosdb-attributes-v4]

[!INCLUDE functions-cosmosdb-settings-v3]

[!INCLUDE functions-cosmosdb-settings-v4]


::: zone-end
::: zone pivot="programming-language-java"

Annotations

From the Java functions runtime library, use the @CosmosDBInput annotation on parameters that read data from Cosmos DB. The annotation supports the following properties:

[!INCLUDE functions-cosmosdb-extension-java-note]


::: zone-end
::: zone pivot="programming-language-javascript,programming-language-powershell,programming-language-python"

Configuration

The following table explains the binding configuration properties that you set in the function.json file, where properties differ by extension version:

[!INCLUDE functions-cosmosdb-settings-v3]

[!INCLUDE functions-cosmosdb-settings-v4]


::: zone-end

See the Example section for complete examples.

Usage

The parameter type supported by the Azure Cosmos DB trigger depends on the Functions runtime version, the extension package version, and the C# modality used.

The trigger requires a second collection that it uses to store leases over the partitions. Both the collection being monitored and the collection that contains the leases must be available for the trigger to work.

::: zone pivot="programming-language-csharp"

Important

If multiple functions are configured to use a Cosmos DB trigger for the same collection, each of the functions should use a dedicated lease collection or specify a different LeaseCollectionPrefix for each function. Otherwise, only one of the functions will be triggered. For information about the prefix, see the Configuration section. ::: zone-end ::: zone pivot="programming-language-java,programming-language-javascript,programming-language-powershell,programming-language-python"

Important

If multiple functions are configured to use a Cosmos DB trigger for the same collection, each of the functions should use a dedicated lease collection or specify a different leaseCollectionPrefix for each function. Otherwise, only one of the functions will be triggered. For information about the prefix, see the Configuration section. ::: zone-end

The trigger doesn't indicate whether a document was updated or inserted, it just provides the document itself. If you need to handle updates and inserts differently, you could do that by implementing timestamp fields for insertion or update.

[!INCLUDE functions-cosmosdb-connections]

Next steps