Cassandra维护插入和更新时间戳

时间:2018-09-27 15:33:11

标签: cassandra timestamp

我有一个表来维护产品数据。 每隔几分钟调用一次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

1 个答案:

答案 0 :(得分:0)

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
相关问题