Sumit Chawla
Sumit Chawla

Reputation: 399

DynamoDB if_not_exists on UpdateItem

I am trying a very simple scenario. I need to maintain a counter per row. I am using UpdateItem to do upsert instead of insert.

  1. If row does not exist, it should just set the value of counter column
  2. If row exists, it should update the counter.

2 works fine, but for 1 it complains that attribute does not exist. I tried if_not_exists clause without any help. Can someone please point me to the right direction? Also share how to use if_not_exists clause for UpdateItem

Upvotes: 6

Views: 12680

Answers (2)

Vladyslav Nikolaiev
Vladyslav Nikolaiev

Reputation: 2029

You could use the DynamoDb update expression like this:

SET #param = if_not_exists(#param, :num0) + :num1

Where :num0 - default value and :num1 - number to add. Please, be aware that the value after the first DynamoDb update operation of the field param would be :num0 + :num1

Upvotes: 10

Sumit Chawla
Sumit Chawla

Reputation: 399

Figured it out. Used ADD operation instead of SET operation to update the counter during upsert

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html

Upvotes: 6

Related Questions