ClickHouse之ReplacingMergeTree详谈
ReplacingMergeTree 是 MergeTree 的一个变种,它存储特性完全继承 MergeTree,只是多了一个去重的功能。
尽管 MergeTree 可以设置主键,但是 primary key 其实没有唯一约束的功能。
如果你想处理掉重复的数据,可以借助这个 ReplacingMergeTree。
去重时机
数据的去重只会在合并的过程中出现。合并会在未知的时间在后台进行,所以你无法预先作出计划。有一些数据可能仍未被处理。
去重范围
如果表经过了分区,去重只会在分区内部进行去重,不能执行跨分区的去重。
所以 ReplacingMergeTree 能力有限,ReplacingMergeTree 适用于在后台清除重复的数据以节省空间,但是它不保证没有重复的数据出现。
案例演示
创建表
create table order_table4
(
id UInt32,
item_id String,
total_amount Decimal(16, 2),
create_time Datetime
) engine = ReplacingMergeTree(create_time)
partition by toYYYYMMDD(create_time) primary key (id)
order by (id, item_id);
ReplacingMergeTree() 填入的参数为表字段,重复数据保留版本字段值最大的。
如果不填表字段,默认按照插入顺序保留最后一条。
插入数据
insert into order_table4
values (101, 's_001', 1000.00, '2020-06-01 12:00:00'),
(102, 's_002', 2000.00, '2020-06-01 11:00:00'),
(102, 's_004', 2500.00, '2020-06-01 12:00:00'),
(102, 's_002', 2000.00, '2020-06-01 13:00:00'),
(102, 's_002', 12000.00, '2020-06-01 13:00:00'),
(102, 's_002', 600.00, '2020-06-02 12:00:00');
执行第一次查询
手动合并
OPTIMIZE TABLE order_table4 FINAL;
再执行一次查询
结论
◼ 实际上是使用 order by 字段作为唯一键
◼ 去重不能跨分区
◼ 只有合并才会进行去重
◼ 认定重复的数据保留,表字段值最大的
◼ 如果表字段相同则按插入顺序保留最后一条
转载自:https://juejin.cn/post/7032086662242893861