I would like to increment a counter in a row only if a certain attribute doesnt exist in the row. I tried this
response = dynamodb.update_item(TableName=table_name,
Key={'id':{'S': id}},
UpdateExpression='SET #att = #att :inc',
ConditionExpression="attribute_not_exists(#a)",
ExpressionAttributeNames={"#att": "counter", "#a": "attribute"},
ExpressionAttributeValues={':inc': {'N': '1'}},
ReturnValues="UPDATED_NEW")
but I get an error
An error occurred (ValidationException) when calling the
UpdateItem operation: The provided expression refers to an
attribute that does not exist in the item
CodePudding user response:
Seems like attribute
exists on the item but counter
doesn’t, so you can’t access the current value of counter
to increment it.
CodePudding user response:
Using "ADD" expression instead of "SET" will create the counter attribute (if it does not exist) then add the value: doc
The query code may look like:
response = dynamodb.update_item(TableName=table_name,
Key={'id':{'S': id}},
UpdateExpression='ADD #att :inc',
ConditionExpression="attribute_not_exists(#a)",
ExpressionAttributeNames={"#att": "counter", "#a": "attribute"},
ExpressionAttributeValues={':inc': {'N': '1'}},
ReturnValues="UPDATED_NEW")