全域性索引與分割槽索引對於SQL效能影響的比較
阿新 • • 發佈:2022-06-01
KingbaseES 提供了對於分割槽表 global index 的支援。global index 不僅提供了對於唯一索引功能的改進(無需包含分割槽鍵),而且在效能上相比非global index (local index)有很大的提升(無法提供分割槽條件情況下)。以下舉例說明二者在效能方面的差異。
1、準備資料
create table t1(id1 integer,id2 integer,name text) partition by hash(id1) partitions 200; insert into t1 select generate_series(1,10000000),generate_series(1,10000000),repeat('a',500);
2、本地索引的效能
沒有提供分割槽條件時
create index ind_t1_id2 on t1(id2); test=# \di+ ind_t1_id2 List of relations Schema | Name | Type | Owner | Table | Size | Description --------+------------+-------------------+--------+-------+---------+------------- public| ind_t1_id2 | partitioned index | system | t1 | 0 bytes | (1 row) test=# explain analyze select * from t1 where id2=10004; QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- Append (cost=0.29..1662.50 rows=200 width=512) (actual time=1.324..3.249 rows=1 loops=1) -> Index Scan using t1_p0_id2_idx on t1_p0 (cost=0.29..8.31 rows=1 width=512) (actual time=0.054..0.055 rows=0 loops=1) Index Cond: (id2 = 10004) -> Index Scan using t1_p1_id2_idx on t1_p1 (cost=0.29..8.31 rows=1 width=512) (actual time=0.065..0.065 rows=0 loops=1) Index Cond: (id2 = 10004) ...... -> Index Scan using t1_p198_id2_idx on t1_p198 (cost=0.29..8.31 rows=1 width=512) (actual time=0.031..0.031 rows=0 loops=1) Index Cond: (id2 = 10004) -> Index Scan using t1_p199_id2_idx on t1_p199 (cost=0.29..8.31 rows=1 width=512) (actual time=0.025..0.025 rows=0 loops=1) Index Cond: (id2 = 10004) Planning Time: 39.262 ms Execution Time: 5.673 ms (403 rows)
使用非全域性索引,並且沒有提供分割槽條件情況下,優化器需要讀取所有索引分割槽及表分割槽的統計資料,才能確定最優的執行計劃。對於資料訪問,同樣需要訪問所有分割槽的索引(即使該分割槽沒有所需要的資料)。
提供分割槽條件時
test=# explain analyze select * from t1 where id2=10004 and id1=10004;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
Index Scan using t1_p71_id2_idx on t1_p71 (cost=0.29..8.31 rows=1 width=512) (actual time=0.045..0.046 rows=1 loops=1)
Index Cond: (id2 = 10004)
Filter: (id1 = 10004)
Planning Time: 0.346 ms
Execution Time: 0.064 ms
(5 rows)
在提供分割槽條件情況下,只需要訪問單個索引分割槽及表分割槽的統計資料,因此,所需的語句的解析時間更少。
3、全域性索引的效能
create unique index ind_t1_id2 on t1(id2) global; test=# \di+ ind_t1_id2 List of relations Schema | Name | Type | Owner | Table | Size | Description --------+------------+--------------+--------+-------+--------+------------- public | ind_t1_id2 | global index | system | t1 | 215 MB | (1 row) test=# explain analyze select * from t1 where id2=10004; QUERY PLAN -------------------------------------------------------------------------------------------------------------------------- Global Index Scan using ind_t1_id2 on t1 (cost=0.38..8.39 rows=200 width=512) (actual time=0.136..0.137 rows=1 loops=1) Index Cond: (id2 = 10004) Planning Time: 9.896 ms Execution Time: 0.264 ms (4 rows)
可以SQL 解析與執行時間都比本地索引的情景快很多。