Cosmos Db Trigger is not being run when inserting new document

Viewed 1388

I am using Azure Cosmos DB. I have created a simple trigger in Azure Portal as follows:

enter image description here

  var context = getContext();
  var request = context.getRequest();

  // item to be created in the current operation
  var itemToCreate = request.getBody();
  itemToCreate["address"] = "test";

  // update the item that will be created
  request.setBody(itemToCreate);

Unfortunately this trigger is not being triggered when I insert new documents. I have also tried to set the "Trigger Type" to "Post". Am I missing anything?

3 Answers

Great question! I always thought that triggers would run automatically :).

I believe the triggers are not run automatically whenever a document is inserted. What you would need to do is specify the trigger that you want to run when you're creating the document.

What you need to do is register the trigger by passing the trigger name as the request option when sending create document request.

For example, see the code here: https://docs.microsoft.com/en-us/azure/cosmos-db/how-to-use-stored-procedures-triggers-udfs#pre-triggers (copied below as well). Notice the use of PreTriggerInclude in RequestOptions:

dynamic newItem = new
{
    category = "Personal",
    name = "Groceries",
    description = "Pick up strawberries",
    isComplete = false
};

Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
RequestOptions requestOptions = new RequestOptions { PreTriggerInclude = new List<string> { "trgPreValidateToDoItemTimestamp" } };
await client.CreateDocumentAsync(containerUri, newItem, requestOptions);

Firing triggers automatically in relational databases makes sense since there is schema in the database, you kind of know what to handle in a trigger logic. In NoSQL database, since there is no schema, you may end up with a large script to handle all kind of exceptions. Large script in triggers means higher bills in Cloud. Making triggers automatic can make many customers bill really high specially in IOT solutions. You can read about Azure Cosmos DB pre/post triggers in my post. https://h-savran.blogspot.com/2020/03/create-triggers.html

The only way according to the answers from @Guarav Mantri and @Hasan Savaran is to specify the trigger while creating the item through the API. I have managed to do it in Java Azure SDK like that:

 RequestOptions options = new RequestOptions();
 options.setPreTriggerInclude(Arrays.asList("pre"));
 documentClient.createDocument(
                    collectionLink(),
                    documentToAdd,
                    options,
                    true);

Although I am not happy with this solution because for instance the trigger will not be triggered when creating the item via Portal.

Related