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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

following the question, the above as code is: .withUpdateExpression("ADD #c :val)")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.