本文介绍了是否可以在 DynamoDB 中进行条件放置或更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 DynamoDB 中存储具有以下结构的记录:

Let's say that I am storing records with following structure in DynamoDB:

{
    "id": "57cf5b43-f9ec-4796-9de6-6a50f556cfd8",
    "created_at": "2015-09-18T13:27:00+12:00",
    "count": 3
}

现在,是否有可能在一个请求中实现以下目标:

Now, is it possible to achieve the following in one request:

  • 如果具有给定 id 的记录不存在,则应使用 count = 1 创建它
  • 如果该 id 的记录存在,则计数器正在更新.
  • if the record with given id doesn't exist it should be created with count = 1
  • if the record for that id exists the counter is being updated.

目前我正在查询记录是否存在,并根据结果执行 putupdate.将它折叠成一个操作会很好.

Currently I'm doing a query to check if the record exist and depending on the result I do a put or an update. It would be nice to fold that into a single operation.

推荐答案

您可以使用 UpdateItem API 和 UpdateExpression 因为您的用例.由于此处的 count 将是 Number 类型,因此您可以使用 SETADD 表达式:

You can do this with UpdateItem API and the UpdateExpression because of your use case. Since count will be a Number type here, you can use the SET or ADD expressions:

ADD 的文档告诉您可以将它用于 Number 类型(强调我的):

The documentation for ADD tells you that you can use it for Number types (emphasis mine):

  • ADD - 如果该属性尚不存在,则将指定的值添加到项目.如果属性确实存在,那么 ADD 的行为取决于属性的数据类型:

  • 如果现有属性是一个数字,并且如果 Value 也是一个数字,那么 Value 会以数学方式添加到现有属性中.如果 Value 为负数,则从现有属性中减去.
  • If the existing attribute is a number, and if Value is also a number, then Value is mathematically added to the existing attribute. If Value is a negative number, then it is subtracted from the existing attribute.

如果您使用 ADD 来增加或减少更新前不存在的项目的数值,DynamoDB 使用 0 作为初始值.类似地,如果您将 ADD 用于现有的item 增加或减少更新前不存在的属性值,DynamoDB 使用 0 作为初始值.例如,假设您要更新的项目没有名为 itemcount 的属性,但您决定将数字 3 添加到此属性中.DynamoDB 将创建 itemcount 属性,将其初始值设置为 0,最后添加 3.结果将是项目中的新 itemcount 属性,值为 3.

If you use ADD to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use ADD for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses 0 as the initial value. For example, suppose that the item you want to update doesn't have an attribute named itemcount, but you decide to ADD the number 3 to this attribute anyway. DynamoDB will create the itemcount attribute, set its initial value to 0, and finally add 3 to it. The result will be a new itemcount attribute in the item, with a value of 3.

对于您的示例,您可以让您的 UpdateExpressionADD #c :n,其中 :n 有一个 /code> 类型,1 是值,#c 具有 ExpressionAttributeName 替换 count.您需要为 count 使用占位符,因为它是 保留字.

For your example, you could have your UpdateExpression be ADD #c :n, where :n has an ExpressionAttributeValue of the Number type, 1 is the value, and #c has the ExpressionAttributeName substitution for count. You need to use a placeholder for count because it is a reserved word.

查看使用更新表达式修改项目和属性

这篇关于是否可以在 DynamoDB 中进行条件放置或更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:06
查看更多