如何解决Clickhouse - 最新记录
我们在一个复制的合并树表中有将近 1B 条记录。
- 主键是 a,b,c
- 我们的应用程序会随着用户的每个操作不断写入此表。 (我们每小时积累近一百万条记录)
- 我们为 (a,b) 的给定唯一组合附加(存储)最新的时间戳 (updated_at)
关键要求是针对给定的 a、b、c 组合提供最新时间戳的汇总
目前,我们正在处理查询
select a,c,sum(x),sum(y)...etc
from table_1
where (a,updated_at) in (select a,max(updated_at) from table_1 group by a,b)
and c in (...)
group by a,c
对子查询的说明
(select a,b)
^ This part is for illustration only.. our app writes latest updated_at for every a,b implying that the clause shown above is more like
(select a,updated_at from tab_1_summary)
[where tab_1_summary has latest record for a given a,b]
注意:我们必须保持分组标准不变。
表格的结构是partition (c) order by (a,updated_at)
问题是,有没有办法编写更好的查询。 (可以更快地返回结果......我们需要从整体处理中减少几秒钟)
仅供参考:我们玩弄物化视图 ReplicatedReplacingMergeTree。但是,考虑到这个表的大小,与上面的查询相比,常量插入 + FINAL 子句不一定工作得很好。
提前致谢!
解决方法
只是为了测试尝试使用 join 而不是 tuple in (tuples):
select t.a,t.b,t.c,sum(x),sum(y)...etc
from table_1 AS t inner join tab_1_summary using (a,b,updated_at)
where c in (...)
group by t.a,t.c
考虑使用 AggregatingMergeTree 预先计算结果指标:
CREATE MATERIALIZED VIEW table_1_mv
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(updated_at)
ORDER BY (updated_at,a,c)
AS SELECT
updated_at,c,sum(x) AS x,/* see [SimpleAggregateFunction data type](https://clickhouse.tech/docs/en/sql-reference/data-types/simpleaggregatefunction/) */
sum(y) AS y,/* For non-simple functions should be used [AggregateFunction data type](https://clickhouse.tech/docs/en/sql-reference/data-types/aggregatefunction/). */
// etc..
FROM table_1
GROUP BY updated_at,c;
并使用这种方式得到结果:
select a,sum(y)...etc
from table_1_mv
where (updated_at,b) in (select updated_at,b from tab_1_summary)
and c in (...)
group by a,c
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。