[英]How to insert an item with an incremental value on an attribute in dynamodb
I'd like to achieve the self incremental feature like mysql
in Dynamodb
.我想在
Dynamodb
中实现like mysql
的自增量功能。 After some search, I can only use updateItem
with an update expression like { ":inc": {N: "1"} }
.经过一番搜索,我只能将
updateItem
与{ ":inc": {N: "1"} }
类的更新表达式一起使用。 But it only works for updating an existing item.但它仅适用于更新现有项目。 What I want to achieve is to increase a
version
field by 1 whenever we insert a new item on dynamodb.我想要实现的是每当我们在 dynamodb 上插入新项目时将
version
字段增加 1。
Is there a buildin feature in dynamodb to achieve this? dynamodb 中是否有内置功能来实现这一点?
DynamoDB does not have an auto incrementing count feature, you'll have to implement that yourself. DynamoDB 没有自动递增计数功能,您必须自己实现。
You could handle this in a transaction, where you insert a new item into DDB and then increment the version
field by 1. This approach has the side effect of making sure the version only increases if the PutItem
operation succeeds.您可以在事务中处理此问题,将新项目插入 DDB,然后将
version
字段增加 1。这种方法具有确保版本仅在PutItem
操作成功时增加的副作用。 This is useful when you include a ConditionExpression
in the PutItem
call to enforce any other business logic.当您在
PutItem
调用中包含ConditionExpression
以强制执行任何其他业务逻辑时,这很有用。 If the condition fails, the version
will not be incremented.如果条件失败,
version
将不会增加。
You could go one step further and implement a strategy known as Optomistic Locking.您可以进一步 go 并实施称为光学锁定的策略。 You would read the
version
field before calling updateItem
.您将在调用
updateItem
之前阅读version
字段。 In the call to updateItem
, you would use a conditionExpression
to ensure the number is what you expect.在调用
updateItem
时,您将使用conditionExpression
来确保数字是您所期望的。 If another process updated the version, it will fail the condition check and your updateItem
will fail.如果另一个进程更新了版本,它将无法通过条件检查并且您的
updateItem
将失败。 You could try the operation again until you get the outcome you expect.您可以再次尝试该操作,直到获得您期望的结果。
More info about Optimistic Locking: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html有关乐观锁定的更多信息: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.