简体   繁体   English

如何根据条件更新 DynamoDB 项目的属性?

[英]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:我想更新 DynamoDB 上的一个项目,但它的一个特定属性只有在数据库中不为 NULL 时才应更改:

Say the current item in the DB looks like this:假设数据库中的当前项目如下所示:

PK PK SK SK attribute1属性1 attribute2属性2
MYPK MYPK some-id1一些-id1 old value旧值 old stuff老东西
MYPK MYPK some-id2一些-id2 NULL无效的 old stuff老东西

Now locally I set attribute1 to new value and attribute2 to new stuff .现在我在本地将 attribute1 设置为new value并将 attribute2 设置为new stuff What I want to obtain after saving to the database is:保存到数据库后我想要获得的是:

PK PK SK SK attribute1属性1 attribute2属性2
MYPK MYPK some-id1一些-id1 old value new stuff新的东西
MYPK MYPK some-id2一些-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.注意attribute2 是如何为两者更新的,但attribute1 只在它为NULL 的地方更新:在其他地方保留现有值。

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.我知道如果根本没有设置属性 1,我可以在 UpdateExpression 中使用if_not_exists()来执行此操作,但在我的情况下,属性已经设置好了。

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?有什么方法可以做到这一点(例如使用 UpdateExpression 的某些语法),而无需手动查询数据库并检查 attribute1 的值?

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.理想情况下,您将在每个项目上都有一个“更新时间”时间戳,这样您就可以进行有条件的更新以确保您只写入最新的项目,并重试在读取和写入之间已更新的所有项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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