Create a function triggered by Azure Cosmos DB

Learn how to create a function triggered when data is added to or changed in Azure Cosmos DB. To learn more about Azure Cosmos DB, see Azure Cosmos DB: Serverless database computing using Azure Functions.

Azure Cosmos DB code

Prerequisites

To complete this tutorial:

  • If you don't have an Azure subscription, create a free account before you begin.

Note

Azure Cosmos DB bindings are only supported for use with the SQL API. For all other Azure Cosmos DB APIs, you should access the database from your function by using the static client for your API, including Azure Cosmos DB's API for MongoDB, Cassandra API, Gremlin API, and Table API.

Sign in to Azure

Sign in to the Azure portal with your Azure account.

Create an Azure Cosmos DB account

You must have an Azure Cosmos DB account that uses the SQL API before you create the trigger.

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. On the New page, search for and select Azure Cosmos DB.

  3. On the Azure Cosmos DB page, select Create.

  4. On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name A unique name Enter a name to identify your Azure Cosmos account. Because documents.azure.com is appended to the name that you provide to create your URI, use a unique name.

    The name can only contain lowercase letters, numbers, and the hyphen (-) character. It must be between 3-44 characters in length.
    API The type of account to create Select Core (SQL) to create a document database and query by using SQL syntax.

    The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. Currently, you must create a separate account for each API.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
    Apply Free Tier Discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. Learn more about free tier.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Account Type Production or Non-Production Select Production if the account will be used for a production workload. Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. You can change this value anytime.

    Note

    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Note

    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes

    The new account page for Azure Cosmos DB

  5. Select Review + create. You can skip the Network and Tags sections.

  6. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  7. Select Go to resource to go to the Azure Cosmos DB account page.

    The Azure Cosmos DB account page

Create a function app in Azure

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. In the New page, select Compute > Function App.

  3. On the Basics page, use the function app settings as specified in the following table.

    Setting Suggested value Description
    Subscription Your subscription The subscription under which this new function app is created.
    Resource Group myResourceGroup Name for the new resource group in which to create your function app.
    Function App name Globally unique name Name that identifies your new function app. Valid characters are a-z (case insensitive), 0-9, and -.
    Publish Code Option to publish code files or a Docker container.
    Runtime stack Preferred language Choose a runtime that supports your favorite function programming language. In-portal editing isn't currently supported for Python development.
    Version Version number Choose the version of your installed runtime.
    Region Preferred region Choose a region near you or near other services your functions access.
  4. Select Next : Hosting. On the Hosting page, enter the following settings.

    Setting Suggested value Description
    Storage account Globally unique name Create a storage account used by your function app. Storage account names must be between 3 and 24 characters in length and can contain numbers and lowercase letters only. You can also use an existing account, which must meet the storage account requirements.
    Operating system Windows An operating system is pre-selected for you based on your runtime stack selection, but you can change the setting if necessary. In-portal editing is only supported on Windows.
    Plan Consumption (Serverless) Hosting plan that defines how resources are allocated to your function app. In the default Consumption plan, resources are added dynamically as required by your functions. In this serverless hosting, you pay only for the time your functions run. When you run in an App Service plan, you must manage the scaling of your function app.
  5. Select Next : Monitoring. On the Monitoring page, enter the following settings.

    Setting Suggested value Description
    Application Insights Default Creates an Application Insights resource of the same App name in the nearest supported region. By expanding this setting or selecting Create new, you can change the Application Insights name or choose a different region in an Azure geography where you want to store your data.
  6. Select Review + create to review the app configuration selections.

  7. On the Review + create page, review your settings, and then select Create to provision and deploy the function app.

  8. Select the Notifications icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

  9. Select Go to resource to view your new function app. You can also select Pin to dashboard. Pinning makes it easier to return to this function app resource from your dashboard.

    Deployment notification

Next, you create a function in the new function app.

Create Azure Cosmos DB trigger

  1. In your function app, select Functions from the left menu, and then select Add from the top menu.

  2. On the New Function page, enter cosmos in the search field and then choose the Azure Cosmos DB trigger template.

    Functions page in the Azure portal

  3. Configure the new trigger with the settings as specified in the following table:

    Setting Suggested value Description
    New Function Accept the default name The name of the function.
    Cosmos DB account connection Accept the default new name Select New, the Database Account you created earlier, and then OK. This action creates an application setting for your account connection. This setting is used by the binding to connection to the database.
    Database name Tasks Name of the database that includes the collection to be monitored.
    Collection name Items Name of the collection to be monitored.
    Collection name for leases leases Name of the collection to store the leases.
    Create lease collection if it does not exist Yes Checks for existence of the lease collection and automatically creates it.

    Create the Azure Cosmos DB triggered function

  4. Select Create Function.

    Azure creates the Cosmos DB trigger function.

  5. To display the template-based function code, select Code + Test.

    Cosmos DB function template in C#

    This function template writes the number of documents and the first document ID to the logs.

Next, you connect to your Azure Cosmos DB account and create the Items container in the Tasks database.

Create the Items container

  1. Open a second instance of the Azure portal in a new tab in the browser.

  2. On the left side of the portal, expand the icon bar, type cosmos in the search field, and select Azure Cosmos DB.

    Search for the Azure Cosmos DB service

  3. Choose your Azure Cosmos DB account, then select the Data Explorer.

  4. Under SQL API, choose Tasks database and select New Container.

    Create a container

  5. In Add Container, use the settings shown in the table below the image.

    Define the Tasks container

    Setting Suggested value Description
    Database ID Tasks The name for your new database. This must match the name defined in your function binding.
    Container ID Items The name for the new container. This must match the name defined in your function binding.
    Partition key /category A partition key that distributes data evenly to each partition. Selecting the correct partition key is important in creating a performant container.
    Throughput 400 RU Use the default value. If you want to reduce latency, you can scale up the throughput later.
  6. Click OK to create the Items container. It may take a short time for the container to get created.

After the container specified in the function binding exists, you can test the function by adding items to this new container.

Test the function

  1. Expand the new Items container in Data Explorer, choose Items, then select New Item.

    Create an item in Items container

  2. Replace the contents of the new item with the following content, then choose Save.

    {
        "id": "task1",
        "category": "general",
        "description": "some task"
    }
    
  3. Switch to the first browser tab that contains your function in the portal. Expand the function logs and verify that the new document has triggered the function. See that the task1 document ID value is written to the logs.

    View message in the logs.

  4. (Optional) Go back to your document, make a change, and click Update. Then, go back to the function logs and verify that the update has also triggered the function.

Clean up resources

Other quickstarts in this collection build upon this quickstart. If you plan to work with subsequent quickstarts, tutorials, or with any of the services you have created in this quickstart, do not clean up the resources.

Resources in Azure refer to function apps, functions, storage accounts, and so forth. They're grouped into resource groups, and you can delete everything in a group by deleting the group.

You created resources to complete these quickstarts. You may be billed for these resources, depending on your account status and service pricing. If you don't need the resources anymore, here's how to delete them:

  1. In the Azure portal, go to the Resource group page.

    To get to that page from the function app page, select the Overview tab and then select the link under Resource group.

    Select the resource group to delete from the function app page.

    To get to that page from the dashboard, select Resource groups, and then select the resource group that you used for this quickstart.

  2. In the Resource group page, review the list of included resources, and verify that they're the ones you want to delete.

  3. Select Delete resource group, and follow the instructions.

    Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

Next steps

You have created a function that runs when a document is added or modified in your Azure Cosmos DB. For more information about Azure Cosmos DB triggers, see Azure Cosmos DB bindings for Azure Functions.

Now that you've created your first function, let's add an output binding to the function that writes a message to a Storage queue.