Running an Azure function app each time a CosmosDB document is created and updating documents in a second collection

Viewed 679

I have a scenario, where we have items save in one documentDb collection e.g. under /items/{documentId}. The document looks similar to:

{
    id: [guid],
    rating: 5,
    numReviews: 1
}

I have a second document collection under /user-reviews/{userIdAsPartitionKey}/{documentId}

The document will look like so:

{
    id: [guid],
    itemId: [guidFromItemsCollection],
    userId: [userId],
    rating: 4
}

Upon uploading of this document, I want a trigger to be fired which takes as input this new user rating document, is able to retrieve the relevant document from the items collection, transform the items document based on the new data.

The crux of my problem is: how can I trigger off a document upsert, and how can I retrieve and modify a document from another collection, all within a Funciton App?


I've investigated the following links, which tease at the idea of Triggers being possible on the CosmosDB, but the table suggests we can't hook up a trigger to document DB upload. https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-documentdb

If it's not possible to set up directly, my assumption is I should have a middle tier service handling the upsert (currently using DocumentClient from client side), which can kick off this processing itself, but I like the simplicity of the serverless function apps if possible.

2 Answers

I know this is a pretty old question.

The Change Feed was built for this exact scenario.

In today's Azure Portal, there's even a menu option in the CosmosDB blade that allows you to create and trigger Function based on changes in one collection which allows you to detect and react to changes - i.e. to create a document in another collection.

Related