cassandra - 如何在 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
。由于它是一个非常昂贵的功能,我们不想使用它。
如何为用例设计表和查询。
解决方案
假设我们可以每天“存储”(分区)您的数据,假设一天内不会发生足够的写入以使分区太大。然后,我们可以按time_epoch
DESCending 顺序进行聚类。对于基于时间的数据,按降序存储数据通常最有意义(因为业务需求通常更关心最新数据)。
因此,我会建立一个这样的表:
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
推荐阅读
- r - Determine length of sequences between columns or in string - and paste result
- python - FuzzyWuzzy python, matching two identical phrases in to diverse scripts brought diverse result
- reactjs - Filepond : manually revert to default image
- r - Replace special characters in a dataframe with the normal variant dataframe is empty
- ruby-on-rails - Rails has_many unique scope
- html - 创建带有字体真棒图标的响应式卡片
- database - 使用 Flyway 迁移创建用户
- excel - 通过宏插入表单控制按钮时出现VBA Excel“预期函数或变量”错误
- php - php中的求和数组
- xml - 当我将 XML 文档加载到 Monaco 编辑器时,如何通过鼠标单击或选择获取 XML 信息?