【问题标题】:how to use python-cassandra-driver to insert data with a custom timestamp如何使用 python-cassandra-driver 插入带有自定义时间戳的数据
【发布时间】:2015-12-20 13:53:55
【问题描述】:

我有一个将数据插入 cassandra 表的任务,但我不想覆盖之前插入的记录,但插入 cql 会覆盖现有数据。

还好我找到了一个'USING TIMESTAMP'的操作,时间戳较大的cql会覆盖较小的,否则不会。因此,使用“使用时间戳”我可以使用自定义时间戳来确定是否覆盖。它在 Cqlsh 中运行良好。

但是它在 python-cassandra-driver 中失败了,如何让'USING TIMESTAMP'在 python-cassandra-driver 中工作?我的代码如下:

insert_sql = ("INSERT INTO activate (rowkey, qualifier, info, act_date, log_time) "
              "VALUES(%s, %s, %s, %s, %s) "
              "USING TIMESTAMP %s")
insert_data = (a_string, a_string, a_string, a_string, a_string, a_custom_timestamp)
session.execute(insert_sql, insert_data)

【问题讨论】:

  • 以下布莱克的建议是合理的。专注于您的原始问题:您的代码应该如图所示工作。是什么让您认为它对驱动程序不起作用?这可能是您的自定义时间戳中的分辨率问题吗?你是怎么产生的?

标签: python cassandra datastax


【解决方案1】:

这是设置自定义时间戳的错误用例。不要滥用此功能很重要,因为它可能会产生许多意想不到的副作用,并最终导致数据不可靠。

改用轻量级事务 (LWT)(也使用 PreparedStatements 代替原始字符串!)

stmt = session.prepare("
           INSERT INTO activate (rowkey, qualifier, info, act_date, log_time)
           VALUES (?, ?, ?, ?, ?)
           IF NOT EXISTS
           ")
results = session.execute(stmt, [arg1, arg2, ...])

阅读更多 herehere。 LWT 因不得不触发 paxos 共识检查而受到性能影响,但它比“先读后写”的方法要好。

更好的是,如果您绝对需要最大化写入性能,请考虑修改您的数据模型以包含时间戳:

CREATE TABLE activate (
     rowkey text,
     insert_time timestamp,
     qualifier text,
     info text,
     act_date timestamp,
     log_time timestamp, 
   PRIMARY KEY (rowkey, insert_time));

【讨论】:

猜你喜欢
  • 2015-04-19
  • 2020-01-31
  • 2013-11-09
  • 2014-05-10
  • 2014-11-29
  • 2015-08-24
  • 2017-03-06
  • 2018-07-02
  • 1970-01-01
相关资源
最近更新 更多