如何在 DynamoDB 中创建 UUID? [英] How to make a UUID in DynamoDB?

查看:29
本文介绍了如何在 DynamoDB 中创建 UUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库方案中,我需要一个自动增量主键.我怎样才能实现这个功能?

In my db scheme, I need a autoincrement primary key. How I can realize this feature?

PS 为了访问 DynamoDB,我使用 dynode,Node.js 模块.

PS For access to DynamoDB, I use dynode, module for Node.js.

推荐答案

免责声明:我是 Dynamodb-mapper 项目的维护者

Disclaimer: I am the maintainer of the Dynamodb-mapper project

自动递增键的直观工作流程:

Intuitive workflow of an auto-increment key:

  1. 获取最后的计数器位置
  2. 加1
  3. 使用新编号作为对象的索引
  4. 保存新的计数器值
  5. 保存对象

这只是为了解释潜在的想法.永远不要这样做,因为它不是原子的.在某些工作负载下,您可能会将相同的 ID 分配给 2 个以上不同的对象,因为它不是原子的.这会导致数据丢失.

This is just to explain the underlying idea. Never do it this way because it's not atomic. Under certain workload, you may allocate the same ID to 2+ different objects because it's not atomic. This would result in a data loss.

解决方案是使用原子添加操作以及UpdateItem:

The solution is to use the atomic ADD operation along with ALL_NEW of UpdateItem:

  1. 自动生成一个 ID
  2. 使用新编号作为对象的索引
  3. 保存对象

在最坏的情况下,应用程序在保存对象之前崩溃,但绝不会冒险分配相同的 ID 两次.

In the worst case scenario, the application crashes before the object is saved but never risk to allocate the same ID twice.

还有一个问题:最后一个 ID 值存储在哪里?我们选择了:

There is one remaining problem: where to store the last ID value ? We chose:

{
    "hash_key"=-1, #0 was judged too risky as it is the default value for integers.
    "__max_hash_key__y"=N
}

当然,为了可靠地工作,所有插入数据的应用程序都必须知道这个系统,否则你可能(再次)覆盖数据.

Of course, to work reliably, all applications inserting data MUST be aware of this system otherwise you might (again) overwrite data.

最后一步是自动化流程.例如:

the last step is to automate the process. For example:

When hash_key is 0:
    atomically_allocate_ID()
actual_save()

有关实现细节(Python,抱歉),请参阅https:///bitbucket.org/Ludia/dynamodb-mapper/src/8173d0e8b55d/dynamodb_mapper/model.py#cl-67

For implementation details (Python, sorry), see https://bitbucket.org/Ludia/dynamodb-mapper/src/8173d0e8b55d/dynamodb_mapper/model.py#cl-67

说实话,我的公司没有在生产中使用它,因为在大多数情况下,最好找到另一个键,例如,对于用户,ID,对于交易,日期时间,...

To tell you the truth, my company does not use it in production because, most of the time it is better to find another key like, for the user, an ID, for a transaction, a datetime, ...

我在 dynamodb-mapper 的文档中写了一些例子 并且它可以很容易地外推到 Node.JS

I wrote some examples in dynamodb-mapper's documentation and it can easily be extrapolate to Node.JS

如果您有任何问题,请随时提问.

If you have any question, feel free to ask.

这篇关于如何在 DynamoDB 中创建 UUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆