DynamoDB Transactions API: unable to `addConditionCheck` on the same item to be updated in the same transactionWriteRequest?

Viewed 3359

I am trying to do some operations on a DynamoDB table in a single transaction by following the official Transaction Operations document.


What I am trying to do is:

For a specific record (identified by its primary key), update it only if a specific attribute of it meets some condition.

I do this with DynamoDBMapper.

TransactionWriteRequest transactionWriteRequest = new TransactionWriteRequest();
transactionWriteRequest.addUpdate(obj);
transactionWriteRequest.addConditionCheck(obj, new DynamoDBTransactionWriteExpression().withConditionExpression("attribute_exists(attr1)"));

What this code does is: Update obj in DB with the obj attribute values only if in the corresponding row in DB, row.attr1 == obj.attr1.

However, I keep getting this error

! com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: 
Transaction request cannot include multiple operations on one item
(Service: AmazonDynamoDBv2; 
Status Code: 400; 
Error Code: ValidationException; 
Request ID: UPBT23M5C6HK2S9DO51OAGK1CNVV4KQNSO5AEMVJF66Q9ASUAAJG)

I believe the reason is that addUpdate() and addConditionCheck() are considered two operations on the same row in db that corresponds to obj.


But I don't understand why this is not allowed, because this seems to be a very basic case of maintaining transactions, where we want to make sure a specific row is not updated by other threads after we read and before we update it.

Am I missing something? If this is not allowed, how should I do it otherwise?

1 Answers

The condition check operation is used when you need to check a condition, but you don’t want to write to that item. If you want to check a condition on the item you are writing, you should add a ConditionExpression to the write operation.

There are two condition check examples on the page you have linked. If you want to check the condition of the item you are updating, you should follow the example method testPutWithConditionalUpdateInTransactionWrite().

Related