Tuesday, March 3, 2020

Step by Step Creating Pre/Post Triggers in Azure Cosmos DB

   
     You have options if you need to use any type of triggers in Cosmos DB. There are two types of triggers in Cosmos DB. First one which I will cover here is the regular triggers which can be executed before (Pre-Triggers) or after (Post-Triggers) an operation. This type of triggers is written in JavaScript and you need to register them to a collection just like stored procedures. Second type of triggers can be created by Azure Functions and you can find more information about them in my older posts.

     Pre-Triggers and Post-Triggers do not take any input parameters. Since Cosmos DB needs to work more work to execute triggers, you will end up with higher Request Units for your queries. They might name triggers, but both do not get executed automatically with every operation. You need to call them programmatically if you want to run them.  If trigger throws any error for any reason, transaction will roll back and data will not be saved to the database.

     When you create any trigger, you can specify what type of operation can use the trigger by using TriggerOperation class.

Available options are

TriggerOperation.All
TriggerOperation.Create
TriggerOperation.Update
TriggerOperation.Delete
TriggerOperation.Replace

     You will have access to current request message in Pre-Trigger, you will have chance to change, verify or validate the data before you do any type of operations. In Post-Trigger, you can verify the data and decide if you need to do any other extra work depending on what is just changed to the database. Just like Stored Procedures, Triggers are scoped to a partition key and items in different partition key will not accessible. In other words, if you want to use them. Use them for the current operation and current data not for the rest of the data in your database.

     You can create triggers from SDK, REST API or from the Data Explorer in Azure Portal. I will show you how to create them from the Portal in this post. First select the collection in Data Explorer and look for the Create Stored Procedure menu on top


Select the new Trigger option and you should see the following page.


     Give a name to your trigger and select a type for it then you are ready to write a JavaScript function. In the following JavaScript, I check the current request to be sure there is a soldby property in the JSON document. If property is not there, I tag this document.

function validateSoldItem() { 
  var context = getContext(); 
  var request = context.getRequest(); 
  // this is the current request 
  var itemToCreate = request.getBody(); 
  // item might need attention
  if (!("soldby" in itemToCreate)) 
  {  
      itemToCreate["needsattention"] = true
  } 
  // update the current request
  request.setBody(itemToCreate); 
}

     As I said before, you need to call this trigger from SDK or REST API. It will not get fired itself. Here is an example how to use the trigger by using .NET SDK 3

public async Task<double> CreateItem(SoldItem item)
{
    var response = await cosmosClient.GetContainer(_dbname, _container)
           .CreateItemAsync(item, null, new ItemRequestOptions 
           { PreTriggers = new List<string> { "validateSoldItem" } });
    return response.RequestCharge;
}

3 comments:

  1. I think there is a need to provide some more information about SQL and even its other elements and aspects.Trigger is very useful and provides database security as well.

    SQL Server Load Rest API


    ReplyDelete
  2. im trying to implement a sp that helps me to update partially data, is it possible in cosmos bd to query the PartitionKey and an object, then, do the update of these objects ?
    Thanks

    ReplyDelete
  3. can we auto run trigger in cosumos db

    ReplyDelete