如何在 Cassandra 中创建自增 ID [英] How to create auto increment IDs in Cassandra
本文介绍了如何在 Cassandra 中创建自增 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们知道在 SQL 数据库中创建自增 ID 很容易,在 Cassandra 中有没有好的解决方案?ID 应该用于键名或列名.
We know that it is easy to create auto increment IDs in SQL databases, is there a good solution for it in Cassandra? The IDs should be for key or column name.
推荐答案
以下如何,使用 Cassandra 的 轻量级交易
How about the following, using Cassandra's Lightweight transactions
CREATE TABLE ids (
id_name varchar,
next_id int,
PRIMARY KEY (id_name)
)
2 - 插入您想使用全局序列的每个 id
例如:
INSERT INTO ids (id_name, next_id)
VALUES ('person_id', 1)
3 - 然后,当插入到要使用自动递增键的表时,请执行以下操作:
3.1 - 从 ids 表中获取 next_id:
SELECT next_id FROM ids WHERE id_name = 'person_id'
假设结果是 next_id = 1
Let's say the result is next_id = 1
UPDATE ids SET next_id = 2 WHERE id_name = 'person_id' IF next_id = 1
结果应该是这样的:
[{[applied]: True}]
如果更新成功,或者
[{[applied]: False, next_id: 2}]
如果其他人已经更新了.
If someone else has already updated it.
因此,如果您得到 True,请使用 id '1' - 它是您的.否则,增加next_id(或仅使用返回的next_id)并重复该过程.
So, if you got True, use id '1' - it is yours. Otherwise, increment next_id (or just use the returned next_id) and repeat the process.
这篇关于如何在 Cassandra 中创建自增 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文