Search code examples
amazon-dynamodb

Is it possible to update a value conditionally in DynamoDB?


Suppose I'm storing records with the following structure in DynamoDB:

{
    "id": "574edeac445084d8d5aacc99b941d9d6",
    "status": "NEW",
    "blocked": false
}

Is it possible to achieve the following in one request?

If the record with the given id is blocked update status to BLOCKED or else to APPROVED


Solution

  • Unfortunately, no. In a single request, you can include a ConditionExpression that will either:

    1. perform the update if the condition evaluates true or
    2. abort the update if the condition evaluates false

    For your implementation it seems like you would need support for some kind of if ... else UpdateExpression function, which according to the list of comparison and function references for update expressions, is not available.

    If this is not an extremely frequent operation, multiple requests would likely be fine. I can think of two options there:

    1. Perform a GET request and then in your application compute the value you want to send in the UPDATE based on the response from the GET.
    2. Attempt a "blind" UPDATE request with the ConditionExpression that you anticipate will yield the most success, and if it fails, compute the new value and send it with a second UPDATE request.

    For example: if you think that one condition expression will evaluate true 3/4's of the time, then you're only making two update requests 25% of the time. If you use the GET method above you're making a GET and an UPDATE 100% of the time. If there's a 50/50 chance that the first "blind" UPDATE attempt will fail, it might be easier to just use option number 1.

    If this is an extremely popular operation, you may want to rethink your table design. You might be able to leverage sparse indexes to accomplish your goal.