DynamoDB: updateItem only if it already exists
Use conditional expression id = :id
where id
is the attribute name (or primary key name in your case) and :id
is the value (key of the item you want to update).
Conditional expression is always evaluated before any writing. If that expression doesn't evaluate to true
(and it doesn't if that key doesn't exist or is different), it doesn't update or put a new item.
The key point is that ConditionExpression
is reviewed on different data sets depending on the operation you're performing PutItem or UpdateItem.
PutItem.
When setting ConditionExpression
DynamoDB will check your condition on any of the Key rows - many rows if using range attribute on the table or just 1 if only using a hash for your table -.
Remember DynamoDB PutItem operation has to check if the Key you pass already exists, so no extra cost for checking your condition here.
For example, if you have a CUSTOMER_CONTACTS table with customer_id/contact_email key definition and don't want to create duplicates, you can set ConditionExpression = "#contact_email <> :email"
. In that case PutItem operation will fail with ConditionalCheckFailedException if the same email (range attribute) is used for the specified hash value.
But don't expect to check for item attributes far from your hash rows. No sense for DynamoDB to scan all the table just for checking your condition.
Update Item.
If you try the same condition as for previous example ConditionExpression = "#contact_email <> :email"
the operation is always overriding without triggering an exception. Why? Because UpdateItem is just looking at 1 item, the one specified by your Key.
When using UpdateItem the ConditionExpression will look at only 1 row, the one specified by the Key values you have to set. No way to check your condition on any other table row.
You probably looking for attribute_not_exists
check in Condition Expressions
.
When this conditional expression is used with the PutItem, DynamoDB first looks for an item whose primary key matches that of the item to be written. Only if the search returns nothing is there no partition key present in the result. Otherwise, the attribute_not_exists function above fails and the write will be prevented