Reputation: 3607
How can I programmatically change just the key of a nested map in DynamoDB without also changing the value of that map?
For example, see the game
table I created below. I want to change the name "Sam" to "Steve" without having to add a new key/value pair to the map. In the GUI I can just change the name and click save, but I can't find an example of how to do this programmatically.
Is it possible to just change the key? Or do I need to create a new key "Steve", copy the contents of "Sam" to "Steve", and then delete the "Sam" key?
EDIT: note that I don't want to overwrite the whole scores
map, as I don't want to accidentally overwrite other changes that are being made to this record concurrently.
Upvotes: 2
Views: 1318
Reputation: 13711
No, you cannot change the key of a map entry - but you can do something similar with an UpdateExpression
which copies the old entry to a new nested key, and then delete the old one. For example, SET scores.#newname = scores.#oldname REMOVE scores.#oldname
(with #oldname
and #newname
set in an ExpressionAttributeNames
).
This expression will copy the value of scores.Sam into scores.Steve, and then delete scores.Sam. If there are concurrent updates to other members of scores it's not a problem - but it will be a problem if scores.Steve already exists or is created concurrently. So for that you can use a ConditionExpression
- you can ask to perform that Steve-setting operation only if scores.Steve doesn't previously exists. For example the expression can be attribute_not_exists (score.#newname)
- so the operation will only write to score.newname if it doesn't already exist.
Upvotes: 3
Reputation: 25639
Dynamo calls such items nested attributes. DynamoDB supports CRUD operations on nested key-value pairs, but not keys alone.
You can define update expressions targeting individual map or list elements using the AWS CLI or one of the language SDKs. (Tip: You can examine what the DynamoDB console is doing under the hood in the Chrome DevTools Network Tab).
So if a parent key updates, child attributes need to be set as well. If you are concerned about collisions, you can set Condition Expressions that will cause an update to fail if the defined conditions are not met (e.g. if unmodified attribute have changed in the meantime).
Upvotes: 1