前言
最近在搞520大促的事情,忙到腳不點(diǎn)地,所以就寫些簡(jiǎn)單省事的吧。
物化視圖概念
我們都知道,數(shù)據(jù)庫(kù)中的視圖(view)是從一張或多張數(shù)據(jù)庫(kù)表查詢導(dǎo)出的虛擬表,反映基礎(chǔ)表中數(shù)據(jù)的變化,且本身不存儲(chǔ)數(shù)據(jù)。那么物化視圖(materialized view)是什么呢?英文維基中給出的描述是相當(dāng)準(zhǔn)確的,抄錄如下。
In computing, a materialized view is a database object that contains the results of a query. For example, it may be a local copy of data located remotely, or may be a subset of the rows and/or columns of a table or join result, or may be a summary using an aggregate function.
The process of setting up a materialized view is sometimes called materialization. This is a form of caching the results of a query, similar to memoization of the value of a function in functional languages, and it is sometimes described as a form of precomputation. As with other forms of precomputation, database users typically use materialized views for performance reasons, i.e. as a form of optimization.
物化視圖是查詢結(jié)果集的一份持久化存儲(chǔ),所以它與普通視圖完全不同,而非常趨近于表。“查詢結(jié)果集”的范圍很寬泛,可以是基礎(chǔ)表中部分?jǐn)?shù)據(jù)的一份簡(jiǎn)單拷貝,也可以是多表join之后產(chǎn)生的結(jié)果或其子集,或者原始數(shù)據(jù)的聚合指標(biāo)等等。所以,物化視圖不會(huì)隨著基礎(chǔ)表的變化而變化,所以它也稱為快照(snapshot)。如果要更新數(shù)據(jù)的話,需要用戶手動(dòng)進(jìn)行,如周期性執(zhí)行SQL,或利用觸發(fā)器等機(jī)制。
產(chǎn)生物化視圖的過(guò)程就叫做“物化”(materialization)。廣義地講,物化視圖是數(shù)據(jù)庫(kù)中的預(yù)計(jì)算邏輯+顯式緩存,典型的空間換時(shí)間思路。所以用得好的話,它可以避免對(duì)基礎(chǔ)表的頻繁查詢并復(fù)用結(jié)果,從而顯著提升查詢的性能。它當(dāng)然也可以利用一些表的特性,如索引。
在傳統(tǒng)關(guān)系型數(shù)據(jù)庫(kù)中,Oracle、PostgreSQL、SQL Server等都支持物化視圖,作為流處理引擎的Kafka和Spark也支持在流上建立物化視圖。下面來(lái)聊聊ClickHouse里的物化視圖功能。
ClickHouse物化視圖示例
我們目前只是將CK當(dāng)作點(diǎn)擊流數(shù)倉(cāng)來(lái)用,故拿點(diǎn)擊流日志表當(dāng)作基礎(chǔ)表。
CREATE TABLE IF NOT EXISTS ods.analytics_access_log
ON CLUSTER sht_ck_cluster_1 (
ts_date Date,
ts_date_time DateTime,
user_id Int64,
event_type String,
from_type String,
column_type String,
groupon_id Int64,
site_id Int64,
site_name String,
main_site_id Int64,
main_site_name String,
merchandise_id Int64,
merchandise_name String,
-- A lot more other columns......
)
ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/ods/analytics_access_log','{replica}')
PARTITION BY ts_date
ORDER BY (ts_date,toStartOfHour(ts_date_time),main_site_id,site_id,event_type,column_type)
TTL ts_date + INTERVAL 1 MONTH
SETTINGS index_granularity = 8192,
use_minimalistic_part_header_in_zookeeper = 1,
merge_with_ttl_timeout = 86400;
w/ SummingMergeTree
如果要查詢某個(gè)站點(diǎn)一天內(nèi)分時(shí)段的商品點(diǎn)擊量,寫出如下SQL語(yǔ)句。
SELECT toStartOfHour(ts_date_time) AS ts_hour,
merchandise_id,
count() AS pv
FROM ods.analytics_access_log_all
WHERE ts_date = today() AND site_id = 10087
GROUP BY ts_hour,merchandise_id;
這是一個(gè)典型的聚合查詢。如果各個(gè)地域的分析人員都經(jīng)常執(zhí)行該類查詢(只是改變ts_date與site_id的條件而已),那么肯定有相同的語(yǔ)句會(huì)被重復(fù)執(zhí)行多次,每次都會(huì)從analytics_access_log_all這張大的明細(xì)表取數(shù)據(jù),顯然是比較浪費(fèi)資源的。而通過(guò)將CK中的物化視圖與合適的MergeTree引擎配合使用,就可以實(shí)現(xiàn)預(yù)聚合,從物化視圖出數(shù)的效率非常好。
下面就根據(jù)上述SQL語(yǔ)句的查詢條件創(chuàng)建一個(gè)物化視圖,請(qǐng)注意其語(yǔ)法。
CREATE MATERIALIZED VIEW IF NOT EXISTS test.mv_site_merchandise_visit
ON CLUSTER sht_ck_cluster_1
ENGINE = ReplicatedSummingMergeTree('/clickhouse/tables/{shard}/test/mv_site_merchandise_visit','{replica}')
PARTITION BY ts_date
ORDER BY (ts_date,ts_hour,site_id,merchandise_id)
SETTINGS index_granularity = 8192, use_minimalistic_part_header_in_zookeeper = 1
AS SELECT
ts_date,
toStartOfHour(ts_date_time) AS ts_hour,
site_id,
merchandise_id,
count() AS visit
FROM ods.analytics_access_log
GROUP BY ts_date,ts_hour,site_id,merchandise_id;
可見,物化視圖與表一樣,也可以指定表引擎、分區(qū)鍵、主鍵和表設(shè)置參數(shù)。商品點(diǎn)擊量是個(gè)簡(jiǎn)單累加的指標(biāo),所以我們選擇SummingMergeTree作為表引擎(上述是高可用情況,所以用了帶復(fù)制的ReplicatedSummingMergeTree)。該引擎支持以主鍵分組,對(duì)數(shù)值型指標(biāo)做自動(dòng)累加。每當(dāng)表的parts做后臺(tái)merge的時(shí)候,主鍵相同的所有記錄會(huì)被加和合并成一行記錄,大大節(jié)省空間。
用戶在創(chuàng)建物化視圖時(shí),通過(guò)AS SELECT ...
子句從基礎(chǔ)表中查詢需要的列,十分靈活。在默認(rèn)情況下,物化視圖剛剛創(chuàng)建時(shí)沒有數(shù)據(jù),隨著基礎(chǔ)表中的數(shù)據(jù)批量寫入,物化視圖的計(jì)算結(jié)果也逐漸填充起來(lái)。如果需要從歷史數(shù)據(jù)初始化,在AS SELECT
子句的前面加上POPULATE
關(guān)鍵字即可。需要注意,在POPULATE
填充歷史數(shù)據(jù)的期間,新進(jìn)入的這部分?jǐn)?shù)據(jù)會(huì)被忽略掉,所以如果對(duì)準(zhǔn)確性要求非常高,應(yīng)慎用。
執(zhí)行完上述CREATE MATERIALIZED VIEW
語(yǔ)句后,通過(guò)SHOW TABLES
語(yǔ)句查詢,會(huì)發(fā)現(xiàn)有一張名為.inner.[物化視圖名]
的表,這就是持久化物化視圖數(shù)據(jù)的表,當(dāng)然我們是不會(huì)直接操作它的。
SHOW TABLES
┌─name─────────────────────────────┐
│ .inner.mv_site_merchandise_visit │
│ mv_site_merchandise_visit │
└──────────────────────────────────┘
基礎(chǔ)表、物化視圖與物化視圖的underlying table的關(guān)系如下簡(jiǎn)圖所示。
當(dāng)然,在物化視圖上也可以建立分布式表。
CREATE TABLE IF NOT EXISTS test.mv_site_merchandise_visit_all
ON CLUSTER sht_ck_cluster_1
AS test.mv_site_merchandise_visit
ENGINE = Distributed(sht_ck_cluster_1,test,mv_site_merchandise_visit,rand());
查詢物化視圖的風(fēng)格與查詢普通表沒有區(qū)別,返回的就是預(yù)聚合的數(shù)據(jù)了。
SELECT ts_hour,
merchandise_id,
sum(visit) AS visit_sum
FROM test.mv_site_merchandise_visit_all
WHERE ts_date = today() AND site_id = 10087
GROUP BY ts_hour,merchandise_id;
w/ AggregatingMergeTree
SummingMergeTree只能處理累加的情況,如果不只有累加呢?物化視圖還可以配合更加通用的AggregatingMergeTree引擎使用,用戶能夠通過(guò)聚合函數(shù)(aggregate function)來(lái)自定義聚合指標(biāo)。舉個(gè)例子,假設(shè)我們要按各城市的頁(yè)面來(lái)按分鐘統(tǒng)計(jì)PV和UV,就可以創(chuàng)建如下的物化視圖。
CREATE MATERIALIZED VIEW IF NOT EXISTS dw.main_site_minute_pv_uv
ON CLUSTER sht_ck_cluster_1
ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/dw/main_site_minute_pv_uv','{replica}')
PARTITION BY ts_date
ORDER BY (ts_date,ts_minute,main_site_id)
SETTINGS index_granularity = 8192, use_minimalistic_part_header_in_zookeeper = 1
AS SELECT
ts_date,
toStartOfMinute(ts_date_time) as ts_minute,
main_site_id,
sumState(1) as pv,
uniqState(user_id) as uv
FROM ods.analytics_access_log
GROUP BY ts_date,ts_minute,main_site_id;
利用AggregatingMergeTree產(chǎn)生物化視圖時(shí),實(shí)際上是記錄了被聚合指標(biāo)的狀態(tài),所以需要在原本的聚合函數(shù)名(如sum、uniq)之后加上"State"后綴。
創(chuàng)建分布式表的步驟就略去了。而從物化視圖查詢時(shí),相當(dāng)于將被聚合指標(biāo)的狀態(tài)進(jìn)行合并并產(chǎn)生結(jié)果,所以需要在原本的聚合函數(shù)名(如sum、uniq)之后加上"Merge"后綴。-State
和-Merge
語(yǔ)法都是CK規(guī)定好的,稱為聚合函數(shù)的組合器(combinator)。
SELECT ts_date,
formatDateTime(ts_minute,'%H:%M') AS hour_minute,
sumMerge(pv) AS pv,
uniqMerge(uv) AS uv
FROM dw.main_site_minute_pv_uv_all
WHERE ts_date = today() AND main_site_id = 10029
GROUP BY ts_date,hour_minute
ORDER BY hour_minute ASC;
我們也可以通過(guò)查詢system.parts系統(tǒng)表來(lái)查看物化視圖實(shí)際占用的parts信息。
SELECT
partition,
name,
rows,
bytes_on_disk,
modification_time,
min_date,
max_date,
engine
FROM system.parts
WHERE (database = 'dw') AND (table = '.inner.main_site_minute_pv_uv')
┌─partition──┬─name───────────────┬─rows─┬─bytes_on_disk─┬───modification_time─┬───min_date─┬───max_date─┬─engine─────────────────────────┐
│ 2020-05-19 │ 20200519_0_169_18 │ 9162 │ 4540922 │ 2020-05-19 20:33:29 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_170_179_2 │ 318 │ 294479 │ 2020-05-19 20:37:18 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_170_184_3 │ 449 │ 441282 │ 2020-05-19 20:40:24 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_170_189_4 │ 696 │ 594995 │ 2020-05-19 20:47:40 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_180_180_0 │ 40 │ 33416 │ 2020-05-19 20:37:58 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_181_181_0 │ 70 │ 34200 │ 2020-05-19 20:38:44 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_182_182_0 │ 83 │ 35981 │ 2020-05-19 20:39:32 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_183_183_0 │ 77 │ 35786 │ 2020-05-19 20:39:32 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_184_184_0 │ 81 │ 35766 │ 2020-05-19 20:40:19 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_185_185_0 │ 42 │ 32859 │ 2020-05-19 20:41:54 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_186_186_0 │ 83 │ 35750 │ 2020-05-19 20:43:30 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_187_187_0 │ 79 │ 34272 │ 2020-05-19 20:46:45 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_188_188_0 │ 75 │ 33917 │ 2020-05-19 20:46:45 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
│ 2020-05-19 │ 20200519_189_189_0 │ 81 │ 35712 │ 2020-05-19 20:47:35 │ 2020-05-19 │ 2020-05-19 │ ReplicatedAggregatingMergeTree │
└────────────┴────────────────────┴──────┴───────────────┴─────────────────────┴────────────┴────────────┴────────────────────────────────┘
The End
繼續(xù)去忙了,民那晚安吧(啥
后記:
- 如果表數(shù)據(jù)不是只增的,而是有較頻繁的刪除或修改(如接入changelog的表),物化視圖底層需要改用CollapsingMergeTree/VersionedCollapsingMergeTree;
- 如果物化視圖是由兩表join產(chǎn)生的,那么物化視圖僅有在左表插入數(shù)據(jù)時(shí)才更新。如果只有右表插入數(shù)據(jù),則不更新。