【问题标题】:Cassandra maintain insert and update timestampCassandra 维护插入和更新时间戳
【发布时间】:2018-09-27 15:33:11
【问题描述】:

我有一个维护产品数据的表。 我每隔几分钟进行一次 API 调用后更新此表。

假设我有这张桌子。

create table products(  
  id int,  
  name text,  
  created timestamp,  
  updated timestamp,  
  primary_key(id)
);

所以我在 00:00:00 进行 API 调用,我得到了产品列表

[  
 {id:1, name:'product1'},  
 {id:2, name:'product2'}  
]  

我将它插入到我的 cassandra 表中

id |   name   |      created     |      updated  
1  | Product1 | 1/1/2018 00:00:00| 1/1/2018 00:00:00  
2  | Product2 | 1/1/2018 00:00:00| 1/1/2018 00:00:00  

现在在 10 分钟后的第二次 API 调用中,用户删除了 Product1,但创建了 Product3,所以我得到 API 调用输出为

[  
 {id:2, name:'product2'},   
 {id:3, name:'product3'}   
]

我将在我的 cassandra 表中更新它(因为我不想在决定是否插入或更新之前检查记录是否存在)但我想在我的不安查询中维护 product2 的创建时间,以便我知道产品的创建时间以及产品的生命周期。

我是否可以通过 now() 设置它来维护创建的时间戳而不在查询中指定它,然后我继续更新 updatetime 值?

我的桌子应该是这样的

 id |   name   |      created      |      updated
  1 | Product1 | 1/1/2018 00:00:00 | 1/1/2018 00:00:00  
  2 | Product2 | 1/1/2018 00:00:00 | 1/1/2018 00:00:10  
  3 | Product3 | 1/1/2018 00:00:10 | 1/1/2018 00:00:10

【问题讨论】:

    标签: cassandra timestamp


    【解决方案1】:

    TL;DR; 是的。

    您必须知道在 upsert 期间要调用哪些列,这将是唯一被推送到应用程序端的逻辑,但数据模型可以完全按照您的预期工作。

    CREATE TABLE KS.products (
        id int PRIMARY KEY,
        created timestamp,
        name text,
        updated timestamp
    )
    
    INSERT INTO products (id, name, created, updated) 
      VALUES (1, 'TTzV2', toTimeStamp(now()), toTimeStamp(now()));
    INSERT INTO products (id, name, created, updated) 
      VALUES (2, 'smLL301', toTimeStamp(now()), toTimeStamp(now()));
    
    SELECT * FROM KS.products;
    
     id | created                         | name    | updated
    ----+---------------------------------+---------+---------------------------------
      1 | 2018-09-28 17:22:38.502000+0000 |   TTzV2 | 2018-09-28 17:22:38.502000+0000
      2 | 2018-09-28 17:22:39.180000+0000 | smLL301 | 2018-09-28 17:22:39.180000+0000
    

    现在产品更新后,您需要专门化您的 API 以调用其他内容,但使用以下 CQL 您可以得到您所期望的:

    INSERT INTO products (id, updated) VALUES (2, toTimeStamp(now()));
    INSERT INTO products (id, name, created, updated) 
      VALUES (3, 'Gt3X', toTimeStamp(now()), toTimeStamp(now()));
    
    SELECT * FROM KS.products;
    
     id | created                         | name    | updated
    ----+---------------------------------+---------+---------------------------------
      1 | 2018-09-28 17:22:38.502000+0000 |   TTzV2 | 2018-09-28 17:22:38.502000+0000
      2 | 2018-09-28 17:22:39.180000+0000 | smLL301 | 2018-09-28 17:25:38.208000+0000
      3 | 2018-09-28 17:25:38.774000+0000 |    Gt3X | 2018-09-28 17:25:38.774000+0000
    

    【讨论】:

    • 这对我不起作用,我认为实现这一目标的唯一方法是对数据进行非规范化并创建冗余
    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 2017-03-06
    • 2014-05-10
    • 2018-10-06
    • 2013-06-11
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多