ElFik
ElFik

Reputation: 1027

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

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://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings https://learn.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.

Upvotes: 3

Views: 718

Answers (2)

AlexDrenea
AlexDrenea

Reputation: 8039

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.

Upvotes: 1

David Makogon
David Makogon

Reputation: 71030

Operations are scoped to a collection. You cannot trigger an operation in Collection B from an event in Collection A.

You'd either need to implement this in your app tier (as you suggested) or... store both types of documents in the same collection (a common scenario). You might need to add some type of doctype property to help filter your queries, but since documents are schema-free, you can store heterogeneous documents in the same collection.

Also: You mentioned an Azure Function. Within a function, there's nothing stopping you from making multiple database calls (e.g. when something happens in collection a and causes your function to be called, your function can perform an operation in collection b). Just note that this won't be transactional.

Upvotes: 2

Related Questions