Home > Software engineering >  DynamoDB - TransactWrite, how to do If Else condition
DynamoDB - TransactWrite, how to do If Else condition

Time:08-03

An example, a table with a column counter with only 1 row. I want to update this row's counter value based on its current value.

Say if counter is >= 10, set it to 0, otherwise counter . How to achieve this if else clause in TransactWrite?

I can't have two actions in one transaction because Documentation states that it does not allow more than 1 action on the same item.

And of course, the reason I use TransactWrite is because there will be multiple lambda doing this task in parallel.

CodePudding user response:

You cannot do it in one request, transactional or otherwise.

You can get the item, decide what to do, and then update the item in a second request accordingly. You’ll want to keep a version number or timestamp attribute to make sure the item hasn’t changed between the read and write, and use a condition expression to fail if it has.

That’s a common idiom: https://dynobase.dev/dynamodb-locking/

CodePudding user response:

You can't do it the way you like, because if/else is not supported in transactions. There is however a simpler solution.

Just Update the item and increment the counter. Whenever you read the value, you take the counter value modulo 10, and you get the desired behavior, e.g. 123 % 10 = 3 or 10 % 10 = 0.

  • Related