關於openGauss中的虛擬索引

openGaussbaby發表於2024-04-01

關於 openGauss 中的虛擬索引
作為曾經的 Oracle 資深使用者,對於 Oracle 11gR2 版本推出的 invisible Index 感覺一直很良好;因為這對於大部分情況下做最佳化是比較友好的。實際上 openGauss2.0 版本中也提供了類似的功能,下面我們來進行簡單測試。首先我們建立一個測試表用來驗證 openGauss 的虛擬索引功能:

enmotech=# create table test as select * from pg_settings;

INSERT 0 637
enmotech=# select count(1) from test;
count

637
(1 row)
openGauss 中對於虛擬索引的建立,需要藉助相關函式來實現,如下:

enmotech=# select * from hypopg_create_index('create index on test(name)');
indexrelid | indexname
------------+-------------------------
24643 | <24643>ubtree_test_name
(1 row)

enmotech=# set enable_hypo_index = on;
SET
enmotech=#
透過 hypopg_create_index 建立了基於 test(name)的虛擬索引之後,我們開啟會話級引數,讓最佳化器能夠識別索引。

接下來驗證一下索引是否能夠起作用:

enmotech=# explain select name,setting from test where name='checkpoint_timeout';
QUERY PLAN

Index Scan using <24643>ubtree_test_name on test (cost=0.00..8.27 rows=1 width=64)
Index Cond: (name = 'checkpoint_timeout'::text)
(2 rows)

enmotech=#
可以看到透過 explain 的結果來看,該查詢語句能夠使用 Index scan,用到我們所建立的虛擬索引 16395.

那麼對於虛擬索引,是否會分配空間,佔據檔案系統大小呢?同樣也可以使用 openGauss 提供的相關函式進行查詢:

enmotech=# select * from hypopg_estimate_size(24643);
hypopg_estimate_size

8192
(1 row)

enmotech=#
除此之後還提供了一些其他的函式:

hypopg_reset_index 清除所有虛擬索引

hypopg_drop_index 刪除某個虛擬索引

hypopg_display_index 檢視所有建立的虛擬索引

enmotech=# select * from hypopg_estimate_size(24643);
hypopg_estimate_size

8192
(1 row)

enmotech=#
虛擬索引建立後,屬於例項級別、會話級別(其他會話也可以共享)。如果我們沒有手工進行刪除或者清除操作;那麼當重啟資料庫例項之後,openGauss 會自動刪除所有的虛擬索引。

這裡我們重啟了 openGauss 叢集之後,再登入資料庫檢視是否是這樣:

enmotech=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+-------+----------+-------------+-------------+-------------------
enmotech | roger | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | omm | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | omm | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/omm +
| | | | | omm=CTc/omm
template1 | omm | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/omm +
| | | | | omm=CTc/omm
(4 rows)

enmotech=# select * from hypopg_display_index();
indexname | indexrelid | table | column
-----------+------------+-------+--------
(0 rows)

可以看到,openGauss 例項重啟之後,之前所建立的虛擬索引自動被清除。這實際上也 openGauss AI 功能方面的一個小點。非常贊!

相關文章