Cassandra - 如何检索最近的值

标签 cassandra cassandra-2.0 composite-primary-key

我在 Cassandra 2.0.9 中定义了下表:

CREATE TABLE history
(
    histid      uuid,
    ddate           text,       -- Day Date, i.e. 2014-11-20
    valtime         timestamp,  -- value time
    val             text,       --value
    PRIMARY KEY ((histid , ddate), valtime )
)
WITH CLUSTERING ORDER BY (valtime desc)
;

脚本每天在此表中插入数千行。

我需要能够从只知道 histid 的表中进行选择。
但是,我已经使用 (histid , ddate) 对行进行了分区。
意思是,我每行有一整天的历史值。

为了从此表中选择特定的 histid,我还需要提供 ddate 列。
例如:
SELECT * FROM history
WHERE histid= cebc4c80-daa6-11e3-bcc2-005056a975a4
AND ddate = '2014-05-16'
;

要获得最新值,我可以执行以下操作:
SELECT * FROM history
WHERE histid= cebc4c80-daa6-11e3-bcc2-005056a975a4
AND ddate = '2014-05-16'
LIMIT 1
;

但是,如果我想要任何给定 histid 的最新值,我无法在不知道 ddate 的情况下提交查询,因为它是分区键的一部分。

所以......我问,解决这个问题的最佳方法是什么?

这是我所做的,但我不知道它是否合理:

我创建了一个辅助表:
 CREATE TABLE history_date
(
    histid          uuid,
    maxdate         timestamp, -- most recent date
    PRIMARY KEY (histid)
);

当一行被插入到历史表中时,也会使用 (histid, valtime) 将一行插入到这个表中。

然后我们的程序代码可以:
1.  query the history_date table for a particular id
2. take the "maxdate" column (truncate it to yyyy-mm-dd)
3. use the histid and truncated maxdate to query the history table to retrieve the most recent value.

所以这是有效的。但是,这真的不是一个好的解决方案。

有没有更好的方法来做到这一点,也许只有一张 table ?

谢谢你的时间。

最佳答案

您可以尝试的一件事是构建一个在更宽的日期范围内分区的新表,例如 month .这样,您只需要知道要查询的月份。

CREATE TABLE history_by_month(
    histid          uuid,
    ddate           text,       -- Day Date, i.e. 2014-11-20
    valtime         timestamp,  -- value time
    val             text,       --value
    month           text,
    PRIMARY KEY (month, valtime, histid))
WITH CLUSTERING ORDER BY (valtime desc, histid asc);

现在,此查询应返回您要查找的内容:
SELECT * FROM history_by_month
WHERE month = '2014-05'
LIMIT 1;

唯一要记住的是,如果您在一个月内收到太多条目,您的分区可能会过大。如果这成为一个问题,您可能会考虑将重点缩小到一周。

此外,任何仍在 2.0.9 上的人都应该考虑升级。即使是最新的 2.1 补丁级别也更加稳定。

关于Cassandra - 如何检索最近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28174392/

相关文章:

cassandra - 向 Cassandra 集群添加节点

mysql - 如何使用两个外键的两个主键创建一个表?

Oracle 用常量创建复合主键

postgresql - Elixir -- Ecto -- 复合主键和关系

python - 在 cassandra 中处理分页结果

Cassandra 问题 v3.11.3 ... 从表 1 中选择计数 (*)

cassandra - 获取cassandra cql select中的当前日期

java - 如何使用 Astyanax 客户端将 Cassandra 插入到复合列中?

database - Cassandra 中的删除读取和删除突变

cassandra - 如何对表进行建模以根据随时间变化的状态字段运行查询