Reputation: 7736
I want to update the Sort Key of the following DynamoDB item from FILE#789
to FILE#790
. From DynamoDB docs as well as some StackOverflow answers, the right way to do this is to delete the existing item (DeleteItem) and recreate it (PutItem) with the updated primary key, performed with TransactWriteItems.
Item: {
"PK": {
"S": "USER#123"
},
"SK": {
"S": "FILE#789"
},
"fileName": {
"S": "Construction"
}
}
DeleteItem
is straightforward, since I know the composite Primary Key's values. But to re-create the item, I need the most current values of the item's attributes and then perform a PutItem
. Reading the item separately, and then performing a DeleteItem and PutItem within a transaction does not guarantee that the most current values of the item's attributes are used to re-create the item. What is the recommended way to handle an update of an item's Primary Key in this scenario?
Upvotes: 0
Views: 1376
Reputation: 13108
I'd use a variation of Optimistic Locking here. I've written a blog about the concept a while ago if you want to get into details, but here's the basic summary:
Each item gets a version counter that's incremented once you update it. When you want to update an item, you first read it and store the current version number. Then you perform your update and increment the version number. Now you need to write it back to the table and this is when you add a condition. The condition is that the current version of the item needs to be the same as it was when you read the item originally. If that's not the case the write should fail, because somebody else modified the item in the mean time.
Applied to your use case that means:
This way the transaction will fail if the original item has been updated while you were changing it. If it fails, you start at 1) again.
Upvotes: 1