简体   繁体   中英

How can I update a DynamoDB item's attribute based on a condition?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM