我正在尝试插入一些共享行ID的行,并决定坚持使用基于时间的uuid。我能找到的所有文档都说明了如何创建这样的行:
INSERT INTO users (id, name) VALUES (now(), 'Florian')
我正在使用DataStax's cassandra-driver
for Node.js执行查询(其中insertUser
是包含上面查询的 string ):
var r = await client.execute(insertUser)
console.dir(r.rows)
结果如下:
ResultSet {
info:
{ queriedHost: '127.0.0.1:9042',
triedHosts: { '127.0.0.1:9042': null },
speculativeExecutions: 0,
achievedConsistency: 10,
traceId: undefined,
warnings: undefined,
customPayload: undefined,
isSchemaInAgreement: true },
rows: undefined,
rowLength: undefined,
columns: null,
pageState: null,
nextPage: undefined }
如我们所见,结果中没有ID可用于创建相关行。
是否有Cassandra惯用的方式根据同一id创建多行而不生成本地id?
答案 0 :(得分:2)
您应该在查询参数中提供它,而不要依赖CQL now()
函数(该函数返回UUID v1)。
const cassandra = require('cassandra-driver');
const Uuid = cassandra.types.Uuid;
// ...
const query = 'INSERT INTO users (id, name) VALUES (?, ?)';
const id = Uuid.random();
const options = { prepare: true, isIdempotent: true };
const result = await client.execute(query, [ id, 'Florian' ], options);
从客户端生成ID的另一个好处是,它使查询idempotent。
DataStax驱动程序具有丰富的类型系统,您可以在此表中检出CQL类型为JavaScript类型的表示形式:https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/
答案 1 :(得分:0)
这是一个与您的应用程序查询路径有关的问题。通常,在Cassandra数据模型中,您有一种自上而下的方法,即用户如何从一条信息到另一条信息,从一条查询到另一条查询。
创建后,您的users表将需要通过“ id”列进行查询。如果您不确定要设置什么,该如何找回它?
Cassandra是NoSQL数据库。这并不意味着它不是关系。它具有可以强制执行的关系。如果您没有生成ID,或者之前没有ID,那么以后访问该数据的唯一方法就是使用扫描,不建议这样做。
另一种方法是对“ Florian”字符串进行MD5处理。 MD5字符串将是确定性的。
var input_name = "Florian";
var input_id = md5hash(input_name);
// interpolate the variables into a valid CQL using the values
var cql = "INSERT INTO users (id, name) VALUES ('"+input_id+"', '"+input_name+"');";
您可能可以使清洁器更清洁,但是您会得到照片。