物化視圖管理
物化視圖類似于視圖,允許用戶保存經常使用的或復雜的查詢。物化視圖有實際的物理儲存,但不支持直接寫入更新數據。在查詢中引用物化視圖時,數據直接從物化視圖返回。物化視圖的數據不會自動刷新,因此可能不是最新的,但是訪問物化視圖中的數據要比直接或通過視圖訪問底層表中的數據快得多。物化視圖在用戶能夠容忍定期更新數據的情況下擁有巨大的性能優勢。
AnalyticDB PostgreSQL版Serverless版本暫不支持物化視圖功能。
創建物化視圖
使用命令CREATE MATERIALIZED VIEW
創建一個查詢的物化視圖。
CREATE MATERIALIZED VIEW my_materialized_view as
SELECT * FROM people WHERE age > 40
DISTRIBUTED BY (id);
SELECT * from my_materialized_view ORDER BY age;
返回信息如下:
id | name | city | age
------------+------------+------------+-----
004 | zhaoyi | zhenzhou | 44
005 | xuliui | jiaxing | 54
006 | maodi | shanghai | 55
(3 rows)
物化視圖定義中的查詢僅用于填充物化視圖。物化視圖定義和普通表的定義一樣(除了不能指定OID)。DISTRIBUTED BY在創建時可選,若沒有該語句會選擇默認的第一個可分區列進行分區。
物化視圖會忽略存儲在物化視圖中的ORDER BY以及SORT操作。
刷新或禁用物化視圖
使用REFRESH MATERIALIZED VIEW
命令刷新物化視圖數據。
INSERT INTO people VALUES('007','sunshen','shenzhen',60);
SELECT * from my_materialized_view ORDER BY age;
返回信息如下:
id | name | city | age
------------+------------+------------+-----
004 | zhaoyi | zhenzhou | 44
005 | xuliui | jiaxing | 54
006 | maodi | shanghai | 55
(3 rows)
REFRESH MATERIALIZED VIEW my_materialized_view;
SELECT * from my_materialized_view ORDER BY age;
返回信息如下:
id | name | city | age
------------+------------+------------+-----
004 | zhaoyi | zhenzhou | 44
005 | xuliui | jiaxing | 54
006 | maodi | shanghai | 55
007 | sunshen | shenzhen | 60
(4 rows)
使用With NO DATA
子句會刪除當前數據且不生成新數據,還會使物化視圖處于無法掃描狀態。如果試圖查詢無法掃描狀態的物化視圖,將返回一個錯誤。
REFRESH MATERIALIZED VIEW my_materialized_view With NO DATA;
SELECT * from my_materialized_view ORDER BY age;
ERROR: materialized view "my_materialized_view" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.
REFRESH MATERIALIZED VIEW my_materialized_view;
SELECT * from my_materialized_view ORDER BY age;
返回信息如下:
id | name | city | age
------------+------------+------------+-----
004 | zhaoyi | zhenzhou | 44
005 | xuliui | jiaxing | 54
006 | maodi | shanghai | 55
007 | sunshen | shenzhen | 60
(4 rows)
刪除物化視圖
使用DROP MATERIALIZED VIEW
命令刪除一個物化視圖。
CREATE MATERIALIZED VIEW depend_materialized_view as
SELECT * FROM my_materialized_view WHERE age > 50
DISTRIBUTED BY (id);
DROP MATERIALIZED VIEW depend_materialized_view;
使用DROP MATERIALIZED VIEW ... CASCADE
命令還會刪除所有依賴該物化視圖的對象。例如,如果另一個物化視圖依賴于即將被刪除的物化視圖,那么另一個物化視圖也將被刪除。
如果沒有CASCADE選項,DROP MATERIALIZED VIEW命令就會失敗。
CREATE MATERIALIZED VIEW depend_materialized_view as
SELECT * FROM my_materialized_view WHERE age > 50
DISTRIBUTED BY (id);
DROP MATERIALIZED VIEW my_materialized_view;
ERROR: cannot drop materialized view my_materialized_view because other objects depend on it
DETAIL: materialized view depend_materialized_view depends on materialized view my_materialized_view
HINT: Use DROP ... CASCADE to drop the dependent objects too.
DROP MATERIALIZED VIEW my_materialized_view CASCADE;
適用場景
可以容忍數據不是最新或者定期手動更新的場景。
經常使用的或者特別復雜的查詢。
物化視圖結合外部數據源(如OSS外表、MaxCompute外表)可以實現更快的查詢分析。外部數據通過物化視圖實現本地存儲,同時也可以對物化視圖創建索引。