I want to update an item on DynamoDB, but one specific attribute of it should only be changed if it's not NULL in the database:
Say the current item in the DB looks like this:
PK | SK | attribute1 | attribute2 |
---|---|---|---|
MYPK | some-id1 | old value | old stuff |
MYPK | some-id2 | NULL | old stuff |
Now locally I set attribute1 to new value
and attribute2 to new stuff
. What I want to obtain after saving to the database is:
PK | SK | attribute1 | attribute2 |
---|---|---|---|
MYPK | some-id1 | old value | new stuff |
MYPK | some-id2 | new value | new stuff |
Notice how attribute2 was updated for both, but attribute1 was only updated where it was NULL: elsewhere the existing value was kept.
I know that if attribute1 is not set at all I can use if_not_exists()
in the UpdateExpression to do this, but in my case the attribute is already set.
Is there any way to do this (for example with some syntax of UpdateExpression) without having to query the database and check the value of attribute1 manually?
CodePudding user response:
I don't think you can do this with a "blind write", you need to read the item first and construct the update command with the correct arguments.
Ideally you would have an 'updated at' timestamp on each item so you can do a conditional update to make sure you are only writing the latest item, and retry all items that have been updated between read and write.