索引访问方法介绍
支持的索引
mydb=# select * from pg_am;@H_404_7@
oid | amname | amhandler | amtype @H_404_7@
------+--------+----------------------+--------@H_404_7@
2 | heap | heap_tableam_handler | t@H_404_7@
403 | btree | bthandler | i@H_404_7@
405 | hash | hashhandler | i@H_404_7@
783 | gist | gisthandler | i@H_404_7@
2742 | gin | ginhandler | i@H_404_7@
4000 | spgist | spghandler | i@H_404_7@
3580 | brin | brinhandler | i@H_404_7@
(7 rows)@H_404_7@
索引属性
访问方法属性中的四种类型
- can_order: 访问方法能够在创建索引时指定值的排序顺序(仅适用于“ btree”)
- can_unique:支持唯一约束和主键,适用于btree
- can_multi_col:可以在多列创建索引
- can_exclude:支持排它约束
select a.amname, p.name, pg_indexam_has_property(a.oid,p.name)@H_404_7@
from pg_am a,@H_404_7@
unnest(array['can_order','can_unique','can_multi_col','can_exclude']) p(name)@H_404_7@
where a.amname = 'btree'@H_404_7@
order by a.amname;@H_404_7@
@H_404_7@
amname | name | pg_indexam_has_property @H_404_7@
--------+---------------+-------------------------@H_404_7@
btree | can_order | t@H_404_7@
btree | can_unique | t@H_404_7@
btree | can_multi_col | t@H_404_7@
btree | can_exclude | t@H_404_7@
(4 rows)@H_404_7@
特定索引属性
- clusterable:可以根据索引对行进行重新排序(对其进行cluster操作)
- index_scan:支持索引扫描。尽管此属性可能看起来很奇怪,但并非所有索引都能一次返回TID-有些返回结果一次全部返回,并且仅支持位图扫描
- bitmap_scan: 支持位图扫描
- backward_scan:可以按建立索引时指定的相反顺序返回结果
clusterable:可以根据索引对表的行重新排序,直接使用cluster命令,语法如下:
mydb=# \h cluster @H_404_7@
Command: CLUSTER@H_404_7@
Description: cluster a table according to an index@H_404_7@
Syntax:@H_404_7@
CLUSTER [VERBOSE] table_name [ USING index_name ]@H_404_7@
CLUSTER [VERBOSE]@H_404_7@
@H_404_7@
URL: https://www.postgresql.org/docs/13/sql-cluster.html@H_404_7@
列属性
- asc,desc,nulls_first,nulls_last,orderable:这些属性与值的排序有关,只有btree索引支持排序
- distance_orderable:可以按照操作确定的排序顺序返回结果(到目前为止仅适用于GiST和RUM索引)
- returnable:在不访问表的情况下使用索引的可能性,即仅索引扫描的支持
- search_array:支持使用表达式搜索多个值。
- search_nulls:通过IS NULL和IS NOT NULL条件进行搜索的可能性。
select p.name,@H_404_7@
pg_index_column_has_property('tbl_a_pkey'::regclass,1,p.name)@H_404_7@
from unnest(array[@H_404_7@
'asc','desc','nulls_first','nulls_last','orderable','distance_orderable','returnable','search_array','search_nulls']) p(name);@H_404_7@
@H_404_7@
name | pg_index_column_has_property @H_404_7@
--------------------+------------------------------@H_404_7@
asc | t@H_404_7@
desc | f@H_404_7@
nulls_first | f@H_404_7@
nulls_last | t@H_404_7@
orderable | t@H_404_7@
distance_orderable | f@H_404_7@
returnable | t@H_404_7@
search_array | t@H_404_7@
search_nulls | t@H_404_7@
(9 rows)@H_404_7@
操作符类和操作符族
除了需要知道各种操作方法相关的属性之外,我们还需要知道各种不同的操作方法分别支持哪些数据类型和哪些运算符。pg中提供了操作符类和操作符族的概念。
操作符类包含用于索引的最小运算符集(可能还有辅助函数),以操作某种数据类型。
某些操作符族中包括一个操作符类别。此外,如果一个通用的运算符族具有相同的语义,则它们可以包含多个运算符类。例如,integer_ops系列包括类型bigint,integer和smallint的int8_ops,int4_ops和int2_ops类,它们的大小不同但含义相同
可操作的类型
--如整型和日期为例@H_404_7@
select opfname, opcname, opcintype::regtype@H_404_7@
from pg_opclass opc, pg_opfamily opf@H_404_7@
where opf.opfname = 'integer_ops'@H_404_7@
and opc.opcfamily = opf.oid@H_404_7@
and opf.opfmethod = (@H_404_7@
select oid from pg_am where amname = 'btree'@H_404_7@
);@H_404_7@
opfname | opcname | opcintype @H_404_7@
-------------+----------+-----------@H_404_7@
integer_ops | int2_ops | smallint@H_404_7@
integer_ops | int4_ops | integer@H_404_7@
integer_ops | int8_ops | bigint@H_404_7@
(3 rows)@H_404_7@
@H_404_7@
--datetime_ops系列包含用于操作日期(有时间和无时间)的运算符类:@H_404_7@
@H_404_7@
select opfname, opcname, opcintype::regtype@H_404_7@
from pg_opclass opc, pg_opfamily opf@H_404_7@
where opf.opfname = 'datetime_ops'@H_404_7@
and opc.opcfamily = opf.oid@H_404_7@
and opf.opfmethod = (@H_404_7@
select oid from pg_am where amname = 'btree'@H_404_7@
);@H_404_7@
opfname | opcname | opcintype @H_404_7@
--------------+-----------------+-----------------------------@H_404_7@
datetime_ops | date_ops | date@H_404_7@
datetime_ops | timestamptz_ops | timestamp with time zone@H_404_7@
datetime_ops | timestamp_ops | timestamp without time zone@H_404_7@
(3 rows)@H_404_7@
运算符族还可以包括其他运算符,以比较不同类型的值。分组到族中使计划者可以将具有不同类型值的谓词使用索引。一个族还可以包含其他辅助功能。
在大多数情况下,我们不需要了解操作员的族和类。通常,我们只创建索引,默认情况下使用某个运算符类。
但是,我们可以显式指定运算符类。这是当需要显式规范时的一个简单示例:==在排序规则不同于C的数据库中,常规索引不支持LIKE操作:==
explain select * from t where b like 'A%';@H_404_7@
--这种情况我们就可以通过使用操作符类 text_pattern_ops创建索引来克服此限制:@H_404_7@
create index on t(b text_pattern_ops);@H_404_7@
我们可以通过查询这些系统目录解决很多问题,例如:某种访问方法可以操纵哪些数据类型:
btree方法可以操作以下数据类型
select opcname, opcintype::regtype@H_404_7@
from pg_opclass@H_404_7@
where opcmethod = (select oid from pg_am where amname = 'btree')@H_404_7@
order by opcintype::regtype::text;@H_404_7@
opcname | opcintype @H_404_7@
---------------------+-----------------------------@H_404_7@
array_ops | anyarray@H_404_7@
enum_ops | anyenum@H_404_7@
range_ops | anyrange@H_404_7@
int8_ops | bigint@H_404_7@
bit_ops | bit@H_404_7@
varbit_ops | bit varying@H_404_7@
bool_ops | boolean@H_404_7@
bytea_ops | bytea@H_404_7@
char_ops | "char"@H_404_7@
bpchar_pattern_ops | character@H_404_7@
bpchar_ops | character@H_404_7@
date_ops | date@H_404_7@
float8_ops | double precision@H_404_7@
cidr_ops | inet@H_404_7@
inet_ops | inet@H_404_7@
int4_ops | integer@H_404_7@
interval_ops | interval@H_404_7@
jsonb_ops | jsonb@H_404_7@
macaddr_ops | macaddr@H_404_7@
macaddr8_ops | macaddr8@H_404_7@
money_ops | money@H_404_7@
name_ops | name@H_404_7@
numeric_ops | numeric@H_404_7@
oid_ops | oid@H_404_7@
oidvector_ops | oidvector@H_404_7@
pg_lsn_ops | pg_lsn@H_404_7@
float4_ops | real@H_404_7@
record_image_ops | record@H_404_7@
record_ops | record@H_404_7@
int2_ops | smallint@H_404_7@
varchar_pattern_ops | text@H_404_7@
text_ops | text@H_404_7@
varchar_ops | text@H_404_7@
text_pattern_ops | text@H_404_7@
tid_ops | tid@H_404_7@
timestamp_ops | timestamp without time zone@H_404_7@
timestamptz_ops | timestamp with time zone@H_404_7@
time_ops | time without time zone@H_404_7@
timetz_ops | time with time zone@H_404_7@
tsquery_ops | tsquery@H_404_7@
tsvector_ops | tsvector@H_404_7@
uuid_ops | uuid@H_404_7@
xid8_ops | xid8@H_404_7@
(43 rows)@H_404_7@
运算符类包含哪些运算符
select amop.amopopr::regoperator@H_404_7@
from pg_opclass opc, pg_opfamily opf, pg_am am, pg_amop amop@H_404_7@
where opc.opcname = 'array_ops'@H_404_7@
and opf.oid = opc.opcfamily@H_404_7@
and am.oid = opf.opfmethod@H_404_7@
and amop.amopfamily = opc.opcfamily@H_404_7@
and am.amname = 'btree'@H_404_7@
and amop.amoplefttype = opc.opcintype;@H_404_7@
amopopr @H_404_7@
-----------------------@H_404_7@
<(anyarray,anyarray)@H_404_7@
<=(anyarray,anyarray)@H_404_7@
=(anyarray,anyarray)@H_404_7@
>=(anyarray,anyarray)@H_404_7@
>(anyarray,anyarray)@H_404_7@
(5 rows)@H_404_7@
相关数据字典
数据字典 | 描述 |
---|---|
pg_proc | procedure |
pg_operator | operator |
pg_amop | access method’s operator |
pg_opfamily | operator family |
pg_amproc | access method’s support procedure |
pg_type | datatype |
pg_opclass | operator class |
pg_am | access method |
索引支持的新数据类型
--创建一个新的组合类型@H_404_7@
create type complex as (re float, im float);@H_404_7@
@H_404_7@
--创建表@H_404_7@
create table t1(x complex);@H_404_7@
insert into t1 values ((0.0, 10.0)), ((1.0, 3.0)), ((1.0, 1.0));@H_404_7@
insert into t1 values((1.0,2.0)),((2.0,2.0));@H_404_7@
默认情况,对于组合类型排序是分开的,先比较第一个字段再比较第二个,也可以通过其他方式排序。
--创建相关函数@H_404_7@
create function modulus(a complex) returns float as $$@H_404_7@
select sqrt(a.re*a.re + a.im*a.im);@H_404_7@
$$ immutable language sql;@H_404_7@
@H_404_7@
--定义5种操作符函数:@H_404_7@
create function complex_lt(a complex, b complex) returns boolean as $$@H_404_7@
select modulus(a) < modulus(b);@H_404_7@
$$ immutable language sql;@H_404_7@
@H_404_7@
create function complex_le(a complex, b complex) returns boolean as $$@H_404_7@
select modulus(a) <= modulus(b);@H_404_7@
$$ immutable language sql;@H_404_7@
@H_404_7@
create function complex_eq(a complex, b complex) returns boolean as $$@H_404_7@
select modulus(a) = modulus(b);@H_404_7@
$$ immutable language sql;@H_404_7@
@H_404_7@
create function complex_ge(a complex, b complex) returns boolean as $$@H_404_7@
select modulus(a) >= modulus(b);@H_404_7@
$$ immutable language sql;@H_404_7@
@H_404_7@
create function complex_gt(a complex, b complex) returns boolean as $$@H_404_7@
select modulus(a) > modulus(b);@H_404_7@
$$ immutable language sql;@H_404_7@
创建对应的操作符
create operator #<#(leftarg=complex, rightarg=complex, procedure=complex_lt);@H_404_7@
@H_404_7@
create operator #<=#(leftarg=complex, rightarg=complex, procedure=complex_le);@H_404_7@
@H_404_7@
create operator #=#(leftarg=complex, rightarg=complex, procedure=complex_eq);@H_404_7@
@H_404_7@
create operator #>=#(leftarg=complex, rightarg=complex, procedure=complex_ge);@H_404_7@
@H_404_7@
create operator #>#(leftarg=complex, rightarg=complex, procedure=complex_gt);@H_404_7@
@H_404_7@
--比较数字@H_404_7@
select (1.0,1.0)::complex #<# (1.0,3.0)::complex;@H_404_7@
除了整个5个操作符,还需要定义函数:小于返回-1;等于返回0;大于返回1。其他访问方法可能需要定义其他函数
create function complex_cmp(a complex, b complex) returns integer as $$@H_404_7@
select case when modulus(a) < modulus(b) then -1@H_404_7@
when modulus(a) > modulus(b) then 1@H_404_7@
else 0@H_404_7@
end; $$ language sql;@H_404_7@
创建一个操作符类
create operator class complex_ops@H_404_7@
default for type complex@H_404_7@
using btree as@H_404_7@
operator 1 #<#,@H_404_7@
operator 2 #<=#,@H_404_7@
operator 3 #=#,@H_404_7@
operator 4 #>=#,@H_404_7@
operator 5 #>#,@H_404_7@
function 1 complex_cmp(complex,complex);@H_404_7@
@H_404_7@
--查看排序结构@H_404_7@
mydb=# select * from t1 order by x;@H_404_7@
x @H_404_7@
--------@H_404_7@
(1,1)@H_404_7@
(1,3)@H_404_7@
(0,10)@H_404_7@
(3 rows)@H_404_7@
@H_404_7@
--查看可以使用此查询获取支持的函数:@H_404_7@
select amp.amprocnum,@H_404_7@
amp.amproc,@H_404_7@
amp.amproclefttype::regtype,@H_404_7@
amp.amprocrighttype::regtype@H_404_7@
from pg_opfamily opf,@H_404_7@
pg_am am,@H_404_7@
pg_amproc amp@H_404_7@
where opf.opfname = 'complex_ops'@H_404_7@
and opf.opfmethod = am.oid@H_404_7@
and am.amname = 'btree'@H_404_7@
and amp.amprocfamily = opf.oid;@H_404_7@
@H_404_7@
amprocnum | amproc | amproclefttype | amprocrighttype @H_404_7@
-----------+-------------+----------------+-----------------@H_404_7@
1 | complex_cmp | complex | complex@H_404_7@
(1 row)@H_404_7@
管理操作符
--查看 操作符 和操作符类@H_404_7@
select * from pg_operator;@H_404_7@
select * from pg_opclass;@H_404_7@
@H_404_7@
--查看操作符类型@H_404_7@
select o.oid,o.oprname,@H_404_7@
(select t.typname from pg_type t @H_404_7@
where o.oprleft=t.oid) as oprleft,@H_404_7@
(select t.typname from pg_type t@H_404_7@
where o.oprright=t.oid) as oprright@H_404_7@
from pg_operator o where o.oprname like '#%#';@H_404_7@
@H_404_7@
--删除操作符@H_404_7@
drop operator #<# (complex,complex);@H_404_7@
--删除操作类@H_404_7@
DROP OPERATOR CLASS complex_ops using btree;@H_404_7@
@H_404_7@
--删除函数@H_404_7@
select * from pg_proc where proname like 'com%';@H_404_7@
drop function function_name;@H_404_7@
参考资料
- 字典参考:https://www.postgresql.org/docs/12/catalogs.html
- 文章参考:https://www.freesion.com/article/9026599468/
- 官方文档:https://www.postgresql.org/docs/13/functions-info.html#FUNCTIONS-INFO-INDEXAM-PROPS
BTREE索引
重要特征
- B树是平衡的
- B树是多分支的,即每个页面(通常为8 KB)包含许多(数百个)ctid。因此,B树的深度很小,对于非常大的表,实际上可以达到4–5的深度。
- 索引中的数据按非递减顺序排序,(在页面之间和每个页面内部),并且同一级别的页面通过双向列表相互连接。因此,我们可以仅通过列表的一个方向或另一个方向获得有序数据集,而不必每次都返回到根。
无论哪种扫描类型(index scan、index only scan、bitmap scan),使用btree索引都会返回有序的数据。所以,如果在排序列上存在索引,优化器会首先考虑是索引扫描,否则就是先顺序扫描然后排序。
create index idx_t1 on t1(c1 desc);@H_404_7@
--尤其组合索引 ,如果常用排序,可使用如下方法@H_404_7@
create index idx_t1 on t1(c1 desc,c2 asc);@H_404_7@
空值
pg索引可以存储空值,并支持按条件IS NULL和IS NOT NULL进行搜索。
explain select * from t1 where c1 is null;@H_404_7@
在索引中null值存储在索引的一端,取决于创建索引时指定nulls first还是nulls last。
如果查询包括排序,则这一点很重要:如果SELECT命令在其ORDER BY子句中指定的NULL顺序与构建索引指定的顺序相同(NULLS FirsT或NULLS LAST),则可以使用索引,否则将无法使用索引。
在数据库中null是无法和其它值进行比较的
内部结构
Postgresql的btree索引的算法可以参考:src/backend/access/nbtree/README
其中Postgresql 的B-Tree索引页分为几种类别,我们可以通过btpo_flags的值去区分.
Meta page @H_404_7@
root page # btpo_flags=2 @H_404_7@
branch page # btpo_flags=0 @H_404_7@
leaf page # btpo_flags=1 @H_404_7@
leaf&root page # btpo_flags=3@H_404_7@
@H_404_7@
--详情见:src/include/access/nbtree.h@H_404_7@
/* Bits defined in btpo_flags */@H_404_7@
#define BTP_LEAF (1 << 0) /* leaf page, i.e. not internal page */@H_404_7@
#define BTP_ROOT (1 << 1) /* root page (has no parent) */@H_404_7@
#define BTP_DELETED (1 << 2) /* page has been deleted from tree */@H_404_7@
#define BTP_Meta (1 << 3) /* Meta-page */@H_404_7@
#define BTP_HALF_DEAD (1 << 4) /* empty, but still in tree */@H_404_7@
#define BTP_SPLIT_END (1 << 5) /* rightmost page of split group */@H_404_7@
#define BTP_HAS_GARBAGE (1 << 6) /* page has LP_DEAD tuples */@H_404_7@
#define BTP_INCOMPLETE_SPLIT (1 << 7) /* right sibling's downlink is missing */@H_404_7@
其中Meta page和root page是必须有的,Meta page需要一个页来存储,表示指向root page的page id。
随着记录数的增加,一个root page可能存不下所有的heap item,就会有leaf page,甚至branch page,甚至多层的branch page。
一共有几层branch 和 leaf,就用btree page元数据的 level 来表示。
可以通过pageinspect插件研究所以你内部结构
- bt_Metap(relname text):返回record,bt_Metap用来返回关于一个B树索引元页的信息。
- bt_page_stats(relname text, blkno int):返回record,bt_page_stats返回有关
B-树索引单一页面的总计信息 - bt_page_items(relname text, blkno int):返回record,bt_page_items返回一个
B-树索引页面上项的所有细节信息
参考文档
HASH索引
哈希表是根据键(Key)而直接访问在内存储存位置的数据结构。它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做哈希表
索引结构
当插入索引时,让我们计算键的哈希函数。Postgresql中的哈希函数总是返回integer类型,其范围为2的32次方≈40亿个值。存储桶的数量最初等于2,然后根据数据大小动态增加。bucket编号可以使用位算法从哈希码中计算出来。这是我们将放置ctid的bucket。
当搜索索引时,我们计算键的哈希函数并获取bucket编号。现在,仍然需要遍历bucket的内容,并仅返回具有适当哈希码的匹配ctid。由于存储的“hash code - ctid”对是有序的,因此可以高效地完成此操作。
哈希索引包含4种页:Meta page, primary bucket page, overflow page, bitmap page
- Metapage(0号页),包含了HASH索引的控制信息,指导如何找到其他页面(每个bucket的primary page),以及当前存储概貌。其他索引的0号页基本都是这一个套路。
- primary bucket page,hash index将存储划分为多个bucket(逻辑概念),每个bucket中包含若干page(每个bucket的page数量不需要一致),当插入数据时,根据计算得到的哈希,通过映射算法,映射到某个bucket,也就是说数据首先知道应该插入哪个bucket中,然后插入bucket中的primary
page,如果primary page空间不足时,会扩展overflow page,数据写入overflow page。在page中,数据是有序存储(TREE),page内支持二分查找(binary search),而page与page之间是不保证顺序的,所以hash index不支持order by。 - overflow page,是bucket里面的页,当primary page没有足够空间时,扩展的块称为overflow page
- bimap page,记录primary , overflow page是否为空可以被重用
注意bucket, page都没有提供收缩功能,即无法从OS中收缩空间,但是提供了reuse(通过bitmap page跟踪),如果想要减小索引大小的唯一办法就是使用REINDEX或VACUUM FULL命令从头开始重建索引
总结
hash索引介绍:
src/backend/access/hash/README
使用场景:
使用限制:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。