4

I am trying to insert item if it does not exist and set its counter to 1 or increment counter by one when it exists but it doesn't seem to work...

Here is what I have done so far:

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
    .withPrimaryKey("Id", Id)
    .withReturnValues(ReturnValue.ALL_NEW)
    .withUpdateExpression("set #c = if_not_exists(#c = :val, #c + :val)")
    .withNameMap(new NameMap()
        .with("#c", "counter"))
    .withValueMap(new ValueMap()
        .withNumber(":val", 1));

when I change the update expression to set #c = #c + :val it updates existing items but it doesn't insert new item if it does not exist.

set #c = :val seems to work on both exist and not exist but that's not what I need.

Regolith
  • 2,944
  • 9
  • 33
  • 50
Spyros El.
  • 423
  • 3
  • 13
  • Found the answer here http://stackoverflow.com/questions/32777374/is-it-possible-to-do-a-conditional-put-or-update-in-dynamodb This is the right update expression ADD #c :val – Spyros El. Dec 08 '16 at 15:00

1 Answers1

5

You can create and update the item with one UpdateItem call. UpdateExpression would be ADD #c :val because DynamoDB pretends the value of a Number is zero in ADD operations on items that do not exist yet.

Alexander Patrikalakis
  • 5,054
  • 1
  • 30
  • 48