0

I have to update the dynamodb only if key is present and do not want to create a new row if key is not present.

My Syntax is:

PrimaryKey pk = new PrimaryKey("partitionKey", key1, "sortKey", key2);
String updateExpression = "set abc =:s";
String value = "xyz";

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(pk)
                .withUpdateExpression(updateExpression)
                .withValueMap(new ValueMap().withString(":s", value))
                .withConditionExpression(?);
table.updateItem(updateItemSpec);

What should I provide in withConditionExpression. How can I use attribute_exist() here?

Shaggy31
  • 35
  • 1
  • 5

1 Answers1

1

The update item API would create the new item if it doesn't exist. You can use ConditionExpression to stop creating the new item.

ConditionExpression = attribute_exists(partitionKey)

If the key is not found, the API will throw ConditionalCheckFailedException.

  • I shall pass `partitionKey ` which is attribute name or key1 which is the value? And if I want to pass sort key also? – Shaggy31 Jan 13 '21 at 04:14
  • 2
    You need to pass in KEY and not the VALUE. If you want to add more conditions, you can add them too similar to partitionKey with AND boolean operator. Take a look here for more detailed explanation - https://stackoverflow.com/a/50750158/9774855. – Anshul Saraswat Kaul Jan 13 '21 at 04:26
  • Will suggest to try and check DynamoDBMapper functionality. That offers to smoothly operate. It will take care of your use-case on the fly using - @DynamoDBVersionedAttribute, which this mapper supports. – Anshul Saraswat Kaul Jan 13 '21 at 04:29
  • @Shaggy31, would suggest to create a different question for that so it helps the community. And, if your original question is answered, please accept it :) – Anshul Saraswat Kaul Jan 13 '21 at 15:46