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

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

问题描述

在我的db方案中,我需要一个autoincrement主键。我如何实现这个功能?

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

PS对于访问DynamoDB,我使用 dynode 模块.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. add 1

  3. 使用新号码作为对象的索引

  4. 保存新的计数器值

  5. save对象

  1. get the last counter position
  2. add 1
  3. use the new number as the index of the object
  4. save the new counter value
  5. save the object

这只是为了解释基本的想法。不要这样做,因为它不是原子。在某些工作负载下,您可以将相同的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.

解决方案是使用原子ADD 操作以及 ALL_NEW 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,sorry),请参阅 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

为了告诉你真相,我的公司没有在生产中使用它,因为在大多数时候,最好找到另一个键,对于用户来说,对于一个事务,一个datetime,...

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天全站免登陆