【问题标题】:How to get inserted row immediately after query execution in cassandra?如何在 cassandra 中执行查询后立即插入行?
【发布时间】:2018-10-14 03:30:54
【问题描述】:

我正在尝试在 cassandra 中获取最后插入的行,但我收到了 undefined

下面是代码如何查找insert

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (uuid(), ?, ?)";

client.execute(query, [ 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', result.rows[0].id));

【问题讨论】:

  • 你的表上的主键定义是什么样的?
  • 像这样:id uuid PRIMARY KEY
  • @Aaron 抱歉,如果我的问题不够清楚。但一切都结构良好,适用于select。我的问题是我想获得id 和新插入行的其他信息。
  • 我收到此错误:(node:8140) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
  • 所以错误表明 result.rows 不存在或者它不是一个数组。你能 console.log result 发回你得到的吗?

标签: node.js cassandra


【解决方案1】:

记住你正在处理NoSQL(“非关系”)

如果我要在这张桌子上运行SELECT * FROM users LIMIT 1,我的 结果集将包含一行。那一排将是那一排 包含用户名的最低哈希值(我的分区键), 因为这就是 Cassandra 在集群中存储数据的方式。我会 无法知道它是否是最后一个添加的,所以这个 对你没有多大用处。

The workings are very different from those that you might be used to in MySQL.

如果您的系统需要获取最后插入的行的信息,那么您必须在插入之前知道它。

Generating UUID

const Uuid = require('cassandra-driver').types.Uuid;
const id = Uuid.random();

然后您可以使用id 作为准备好的插入查询的另一个值

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (?, ?, ?)";

client.execute(query, [id, 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', id));

【讨论】:

  • 谢谢!生成的 Uuid 是否在所有表和时间上都是唯一的?
猜你喜欢
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多