首页 > 解决方案 > 如何在 Cassandra 主键中查找范围?

问题描述

用例:查找counter特定id范围内的最大值

我想用这些列创建一个表:time_epoch int,t_counter counter

常见的查询是:

select time_epoch, MAX t_counter where time_epoch >= ... and time_epoch < ...

这是为了找到特定时间范围内的计数器。计划将 time_epoch 作为主键。我无法查询数据。它总是要求ALLOW FILTERING。由于它是一个非常昂贵的功能,我们不想使用它。

如何为用例设计表和查询。

标签: cassandraprimary-keycqlperformancecounter

解决方案


假设我们可以每天“存储”(分区)您的数据,假设一天内不会发生足够的写入以使分区太大。然后,我们可以按time_epochDESCending 顺序进行聚类。对于基于时间的数据,按降序存储数据通常最有意义(因为业务需求通常更关心最新数据)。

因此,我会建立一个这样的表:

CREATE TABLE event_counter (
    day bigint,
    time_epoch timestamp,
    t_counter counter,
    PRIMARY KEY(day,time_epoch))
WITH CLUSTERING ORDER BY (time_epoch DESC);

插入几行后,聚类顺序变得明显:

> SELECT * FROM event_counter ;
    WHERE day=20210219 
      AND time_epoch>='2021-02-18 18:00'
      AND time_epoch<'2021-02-19 8:00';

 day      | time_epoch                      | t_counter
----------+---------------------------------+-----------
 20210219 | 2021-02-19 14:09:21.625000+0000 |         1
 20210219 | 2021-02-19 14:08:32.913000+0000 |         2
 20210219 | 2021-02-19 14:08:28.985000+0000 |         1
 20210219 | 2021-02-19 14:08:05.389000+0000 |         1

(4 rows)

现在选择该范围内的 MAXt_counter应该可以工作:

> SELECT day,max(t_counter) as max
FROM event_counter
WHERE day=20210219
  AND time_epoch>='2021-02-18 18:00'
  AND time_epoch<'2021-02-19 09:00';

 day      | max
----------+-----
 20210219 |   2

推荐阅读