DynamoDb Java API

编程入门 行业动态 更新时间:2024-10-27 17:19:10
DynamoDb Java API - 如果计数器增量不存在则插入(DynamoDb Java API - Insert if does not exist on counter increment)

我试图插入项目,如果它不存在,并将其计数器设置为1或在它存在时递增计数器,但它似乎不起作用...

这是我到目前为止所做的:

UpdateItemSpec updateItemSpec = new UpdateItemSpec() .withPrimaryKey("Id", Id) .withReturnValues(ReturnValue.ALL_NEW) .withUpdateExpression("set #c = if_not_exists(#c = :val, #c + :val)") .withNameMap(new NameMap() .with("#c", "counter")) .withValueMap(new ValueMap() .withNumber(":val", 1));

当我更改更新表达式以设置#c = #c +:val时,它会更新现有项目,但如果它不存在则不会插入新项目。

设置#c =:val似乎既可以存在又不存在,但这不是我需要的。

I am trying to insert item if it does not exist and set its counter to 1 or increment counter by one when it exists but it doesn't seem to work...

Here is what I have done so far:

UpdateItemSpec updateItemSpec = new UpdateItemSpec() .withPrimaryKey("Id", Id) .withReturnValues(ReturnValue.ALL_NEW) .withUpdateExpression("set #c = if_not_exists(#c = :val, #c + :val)") .withNameMap(new NameMap() .with("#c", "counter")) .withValueMap(new ValueMap() .withNumber(":val", 1));

when I change the update expression to set #c = #c + :val it updates existing items but it doesn't insert new item if it does not exist.

set #c = :val seems to work on both exist and not exist but that's not what I need.

最满意答案

您可以使用一个UpdateItem调用创建和更新项目。 UpdateExpression将是ADD #c :val因为DynamoDB假装在对尚不存在的项的ADD操作中Number的值为零。

You can create and update the item with one UpdateItem call. UpdateExpression would be ADD #c :val because DynamoDB pretends the value of a Number is zero in ADD operations on items that do not exist yet.

更多推荐

本文发布于:2023-04-27 13:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DynamoDb   Java   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!