详解ClickHouse的ReplaceMergeTree

区别于MergeTree表引擎,ReplacingMergeTree删除重复数据时是通过相同的分区值(ORDER BY的值)

数据去重发生在后台合并数据时,后台合并数据是随机的,所以有时会有一些没处理的数据,可以通过OPTIMIZI来手动合并,官方建议不要指望它,因为OPTIMIZE会读写大量的数据(可能是会从头再合并一的原因吧)

所以,ReplacingMergeTre适用于后台去重数据来节省空间的场景,但不保证没有一个重复的(官方说的,不是我说的)

建一个表

CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
    name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1],
    name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2],
    ...
) ENGINE = ReplacingMergeTree([ver [, is_deleted]])
[PARTITION BY expr]
[ORDER BY expr]
[PRIMARY KEY expr]
[SAMPLE BY expr]
[SETTINGS name=value, clean_deleted_rows=value, ...]

建表参数描述

ver

可选,填入类型UInt*, Date, DateTime or DateTime64

这个字段的作用是在合并时,决定要留下哪一个

原则一:选最新的那个,ver没设置时,替换为最新插入的那一行

原则二:选最大的那个,ver设置时,选择设置值中最大的那一行

例子

-- without ver - the last inserted 'wins'
CREATE TABLE myFirstReplacingMT
(
    `key` Int64,
    `someCol` String,
    `eventTime` DateTime
)
ENGINE = ReplacingMergeTree
ORDER BY key;
​
INSERT INTO myFirstReplacingMT Values (1, 'first', '2020-01-01 01:01:01');
INSERT INTO myFirstReplacingMT Values (1, 'second', '2020-01-01 00:00:00');
​
SELECT * FROM myFirstReplacingMT FINAL;
​
┌─key─┬─someCol─┬───────────eventTime─┐
│   1 │ second  │ 2020-01-01 00:00:00 │
└─────┴─────────┴─────────────────────┘
​
​
-- with ver - the row with the biggest ver 'wins'
CREATE TABLE mySecondReplacingMT
(
    `key` Int64,
    `someCol` String,
    `eventTime` DateTime
)
ENGINE = ReplacingMergeTree(eventTime)
ORDER BY key;
​
INSERT INTO mySecondReplacingMT Values (1, 'first', '2020-01-01 01:01:01');
INSERT INTO mySecondReplacingMT Values (1, 'second', '2020-01-01 00:00:00');
​
SELECT * FROM mySecondReplacingMT FINAL;
​
┌─key─┬─someCol─┬───────────eventTime─┐
│   1 │ first   │ 2020-01-01 01:01:01 │
└─────┴─────────┴─────────────────────┘

is_deleted

ver设置后才能设置is_deleted,用来标记这行数据是否删除,1代表删除(deleted),0代表存在(state)

想真正删除数据, 执行OPTIMIZE ... FINAL CLEANUPOPTIMIZE ... FINAL 或者表引擎配置 clean_deleted_rows 设置为 Always.

例子

-- with ver and is_deleted
CREATE OR REPLACE TABLE myThirdReplacingMT
(
    `key` Int64,
    `someCol` String,
    `eventTime` DateTime,
    `is_deleted` UInt8
)
ENGINE = ReplacingMergeTree(eventTime, is_deleted)
ORDER BY key;
​
INSERT INTO myThirdReplacingMT Values (1, 'first', '2020-01-01 01:01:01', 0);
INSERT INTO myThirdReplacingMT Values (1, 'first', '2020-01-01 01:01:01', 1); 
​
select * from myThirdReplacingMT final;
​
0 rows in set. Elapsed: 0.003 sec.
​
-- 删除is_deleted标记为1的行
OPTIMIZE TABLE myThirdReplacingMT FINAL CLEANUP; 
​
INSERT INTO myThirdReplacingMT Values (1, 'first', '2020-01-01 00:00:00', 0);
​
select * from myThirdReplacingMT final; 
​
┌─key─┬─someCol─┬───────────eventTime─┬─is_deleted─┐
│   1 │ first   │ 2020-01-01 00:00:00 │          0 │
└─────┴─────────┴─────────────────────┴────────────┘

你可能感兴趣的:(clickhouse,数据库,sql)