ansario
ansario

Reputation: 345

DocumentDB Update Partition Key in Trigger

I have a partition key setup in a MM/YYYY format based on current timestamp for records. I also have a PreTrigger to update this value when a record is saved:

function validate() {
    var context = getContext();
    var request = context.getRequest();
    var document = request.getBody();

    var now = new Date(),

    document.PartitionKey = ("0" + (now.getMonth() + 1)).slice(-2) + "/" + now.getFullYear();
    request.setBody(document);
}

However, I receive the following error:

One or more errors occurred.Message: {"Errors":["PartitionKey extracted from document doesn't match the one specified in the header"]}

Are we not able to modify the partition key in a trigger?

Upvotes: 1

Views: 959

Answers (1)

Aravind Krishna R.
Aravind Krishna R.

Reputation: 8003

No, you cannot change the partition key from inside a trigger.

This is because stored procedures/triggers are executed transactionally within the scope of a single partition key. Since DocumentDB is a distributed database, the partition key is required to route the request to the right server/partition.

The best way to do this is from a data access layer that populates the partition key during insertion. On a side note, using timestamp is discouraged as a partition key because it can lead to hot spots (typically data is frequently accessed for the current timestamp/last few hours).

Upvotes: 1

Related Questions