在 DynamoDB 中生成所需长度的 ID [英] Generating id's of desired length in DynamoDB
问题描述
我正在使用 Amazon DynamoDB,我需要一个对象的 id 长度为 10.我认为不可能告诉 Dynamo 自动生成这个长度的 id(如果我错了,我该怎么做)这个?)所以我在考虑使用我定义的长度为 10 的唯一字符串设置对象的字段.做这个的最好方式是什么?为此,自动增量是一个坏主意吗?
I'm working with Amazon DynamoDB and I need an object to have an id of length 10. I think is not possible to tell Dynamo to auto-generate id's of this length (if I'm wrong, how can I do this?) so I was thinking about setting a field of the object with a unique string of length 10 defined by me. What is the best way to do this? Is auto increment a bad idea for this purpose?
推荐答案
DynamoDB 没有任何机制来为新项目生成唯一 ID.但是,您几乎不需要这样的功能,因为您的应用程序可以轻松生成一个 10 字节的随机字符串并将其用作新项的键.
DynamoDB does not have any mechanism for generating unique ids for new items. However, you hardly need such a feature, because your application can easily generate a 10-byte random string and use that as the key for the new item.
如果您担心一百年一次,这个随机密钥会与已经存在的项目的密钥发生冲突,这也很容易解决:您可以在 ConditionExpression
中使用 ConditionExpression
code>PutItem 要求仅创建不存在的项目:
If you're worried that once in a hundred years, this random key will collide with the key of an item that already exists, that's easy to solve too: You can use a ConditionExpression
in PutItem
to ask to only create the item if it doesn't already exist:
- 条件可以是
id <>:id
,其中id
是键列,:id
是我们尝试创建的随机 ID.如果该项目存在(该值不等于本身),这将失败,但如果该项目不存在,则会成功(如果该项目不存在,则认为它不等于任何东西). - 或者更简单,使用条件
attribute_not_exists(id)
.如果该项目不存在,则attribute_not_exists"check 会成功,但如果该项目确实存在,显然它的主键存在,因此 attribute_not_exists 条件将失败.
- The condition can be that
id <> :id
, whereid
is the key column and:id
is the random id we're trying to create. This will fail if the item exists (the value isn't not-equal itself), but will succeed if the item doesn't exist (if the item doesn't exist, it's considered not equal to anything). - Or even simpler, use the condition
attribute_not_exists(id)
. If the item doesn't exist, the "attribute_not_exists" check will succeed, but if the item does exist, obviously its primary key exists so the attribute_not_exists condition will fail.
这篇关于在 DynamoDB 中生成所需长度的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!