微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【INDEX】Postgresql索引介绍

索引访问方法介绍

支持的索引

  1. mydb=# select * from pg_am;@H_404_7@
  2. oid | amname | amhandler | amtype @H_404_7@
  3. ------+--------+----------------------+--------@H_404_7@
  4. 2 | heap | heap_tableam_handler | t@H_404_7@
  5. 403 | btree | bthandler | i@H_404_7@
  6. 405 | hash | hashhandler | i@H_404_7@
  7. 783 | gist | gisthandler | i@H_404_7@
  8. 2742 | gin | ginhandler | i@H_404_7@
  9. 4000 | spgist | spghandler | i@H_404_7@
  10. 3580 | brin | brinhandler | i@H_404_7@
  11. (7 rows)@H_404_7@

索引属性

  • 访问方法属性—pg_indexam_has_property
  • 特定索引的属性—pg_index_has_property
  • 索引中各列的属性—pg_index_column_has_property
访问方法属性中的四种类型
  • can_order: 访问方法能够在创建索引时指定值的排序顺序(仅适用于“ btree”)
  • can_unique:支持唯一约束和主键,适用于btree
  • can_multi_col:可以在多列创建索引
  • can_exclude:支持排它约束
  1. select a.amname, p.name, pg_indexam_has_property(a.oid,p.name)@H_404_7@
  2. from pg_am a,@H_404_7@
  3. unnest(array['can_order','can_unique','can_multi_col','can_exclude']) p(name)@H_404_7@
  4. where a.amname = 'btree'@H_404_7@
  5. order by a.amname;@H_404_7@
  6. @H_404_7@
  7. amname | name | pg_indexam_has_property @H_404_7@
  8. --------+---------------+-------------------------@H_404_7@
  9. btree | can_order | t@H_404_7@
  10. btree | can_unique | t@H_404_7@
  11. btree | can_multi_col | t@H_404_7@
  12. btree | can_exclude | t@H_404_7@
  13. (4 rows)@H_404_7@
特定索引属性
  • clusterable:可以根据索引对行进行重新排序(对其进行cluster操作)
  • index_scan:支持索引扫描。尽管此属性可能看起来很奇怪,但并非所有索引都能一次返回TID-有些返回结果一次全部返回,并且仅支持位图扫描
  • bitmap_scan: 支持位图扫描
  • backward_scan:可以按建立索引时指定的相反顺序返回结果

clusterable:可以根据索引对表的行重新排序,直接使用cluster命令,语法如下:

  1. mydb=# \h cluster @H_404_7@
  2. Command: CLUSTER@H_404_7@
  3. Description: cluster a table according to an index@H_404_7@
  4. Syntax:@H_404_7@
  5. CLUSTER [VERBOSE] table_name [ USING index_name ]@H_404_7@
  6. CLUSTER [VERBOSE]@H_404_7@
  7. @H_404_7@
  8. 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条件进行搜索的可能性。
  1. select p.name,@H_404_7@
  2. pg_index_column_has_property('tbl_a_pkey'::regclass,1,p.name)@H_404_7@
  3. from unnest(array[@H_404_7@
  4. 'asc','desc','nulls_first','nulls_last','orderable','distance_orderable','returnable','search_array','search_nulls']) p(name);@H_404_7@
  5. @H_404_7@
  6. name | pg_index_column_has_property @H_404_7@
  7. --------------------+------------------------------@H_404_7@
  8. asc | t@H_404_7@
  9. desc | f@H_404_7@
  10. nulls_first | f@H_404_7@
  11. nulls_last | t@H_404_7@
  12. orderable | t@H_404_7@
  13. distance_orderable | f@H_404_7@
  14. returnable | t@H_404_7@
  15. search_array | t@H_404_7@
  16. search_nulls | t@H_404_7@
  17. (9 rows)@H_404_7@

操作符类和操作符族

除了需要知道各种操作方法相关的属性之外,我们还需要知道各种不同的操作方法分别支持哪些数据类型和哪些运算符。pg中提供了操作符类和操作符族的概念。

操作符类包含用于索引的最小运算符集(可能还有辅助函数),以操作某种数据类型。

某些操作符族中包括一个操作符类别。此外,如果一个通用的运算符族具有相同的语义,则它们可以包含多个运算符类。例如,integer_ops系列包括类型bigint,integer和smallint的int8_ops,int4_ops和int2_ops类,它们的大小不同但含义相同

可操作的类型
  1. --如整型和日期为例@H_404_7@
  2. select opfname, opcname, opcintype::regtype@H_404_7@
  3. from pg_opclass opc, pg_opfamily opf@H_404_7@
  4. where opf.opfname = 'integer_ops'@H_404_7@
  5. and opc.opcfamily = opf.oid@H_404_7@
  6. and opf.opfmethod = (@H_404_7@
  7. select oid from pg_am where amname = 'btree'@H_404_7@
  8. );@H_404_7@
  9. opfname | opcname | opcintype @H_404_7@
  10. -------------+----------+-----------@H_404_7@
  11. integer_ops | int2_ops | smallint@H_404_7@
  12. integer_ops | int4_ops | integer@H_404_7@
  13. integer_ops | int8_ops | bigint@H_404_7@
  14. (3 rows)@H_404_7@
  15. @H_404_7@
  16. --datetime_ops系列包含用于操作日期(有时间和无时间)的运算符类:@H_404_7@
  17. @H_404_7@
  18. select opfname, opcname, opcintype::regtype@H_404_7@
  19. from pg_opclass opc, pg_opfamily opf@H_404_7@
  20. where opf.opfname = 'datetime_ops'@H_404_7@
  21. and opc.opcfamily = opf.oid@H_404_7@
  22. and opf.opfmethod = (@H_404_7@
  23. select oid from pg_am where amname = 'btree'@H_404_7@
  24. );@H_404_7@
  25. opfname | opcname | opcintype @H_404_7@
  26. --------------+-----------------+-----------------------------@H_404_7@
  27. datetime_ops | date_ops | date@H_404_7@
  28. datetime_ops | timestamptz_ops | timestamp with time zone@H_404_7@
  29. datetime_ops | timestamp_ops | timestamp without time zone@H_404_7@
  30. (3 rows)@H_404_7@

运算符族还可以包括其他运算符,以比较不同类型的值。分组到族中使计划者可以将具有不同类型值的谓词使用索引。一个族还可以包含其他辅助功能
在大多数情况下,我们不需要了解操作员的族和类。通常,我们只创建索引,认情况下使用某个运算符类。

但是,我们可以显式指定运算符类。这是当需要显式规范时的一个简单示例:==在排序规则不同于C的数据库中,常规索引不支持LIKE操作:==

  1. explain select * from t where b like 'A%';@H_404_7@
  2. --这种情况我们就可以通过使用操作符类 text_pattern_ops创建索引来克服此限制:@H_404_7@
  3. create index on t(b text_pattern_ops);@H_404_7@

我们可以通过查询这些系统目录解决很多问题,例如:某种访问方法可以操纵哪些数据类型:

btree方法可以操作以下数据类型

  1. select opcname, opcintype::regtype@H_404_7@
  2. from pg_opclass@H_404_7@
  3. where opcmethod = (select oid from pg_am where amname = 'btree')@H_404_7@
  4. order by opcintype::regtype::text;@H_404_7@
  5. opcname | opcintype @H_404_7@
  6. ---------------------+-----------------------------@H_404_7@
  7. array_ops | anyarray@H_404_7@
  8. enum_ops | anyenum@H_404_7@
  9. range_ops | anyrange@H_404_7@
  10. int8_ops | bigint@H_404_7@
  11. bit_ops | bit@H_404_7@
  12. varbit_ops | bit varying@H_404_7@
  13. bool_ops | boolean@H_404_7@
  14. bytea_ops | bytea@H_404_7@
  15. char_ops | "char"@H_404_7@
  16. bpchar_pattern_ops | character@H_404_7@
  17. bpchar_ops | character@H_404_7@
  18. date_ops | date@H_404_7@
  19. float8_ops | double precision@H_404_7@
  20. cidr_ops | inet@H_404_7@
  21. inet_ops | inet@H_404_7@
  22. int4_ops | integer@H_404_7@
  23. interval_ops | interval@H_404_7@
  24. jsonb_ops | jsonb@H_404_7@
  25. macaddr_ops | macaddr@H_404_7@
  26. macaddr8_ops | macaddr8@H_404_7@
  27. money_ops | money@H_404_7@
  28. name_ops | name@H_404_7@
  29. numeric_ops | numeric@H_404_7@
  30. oid_ops | oid@H_404_7@
  31. oidvector_ops | oidvector@H_404_7@
  32. pg_lsn_ops | pg_lsn@H_404_7@
  33. float4_ops | real@H_404_7@
  34. record_image_ops | record@H_404_7@
  35. record_ops | record@H_404_7@
  36. int2_ops | smallint@H_404_7@
  37. varchar_pattern_ops | text@H_404_7@
  38. text_ops | text@H_404_7@
  39. varchar_ops | text@H_404_7@
  40. text_pattern_ops | text@H_404_7@
  41. tid_ops | tid@H_404_7@
  42. timestamp_ops | timestamp without time zone@H_404_7@
  43. timestamptz_ops | timestamp with time zone@H_404_7@
  44. time_ops | time without time zone@H_404_7@
  45. timetz_ops | time with time zone@H_404_7@
  46. tsquery_ops | tsquery@H_404_7@
  47. tsvector_ops | tsvector@H_404_7@
  48. uuid_ops | uuid@H_404_7@
  49. xid8_ops | xid8@H_404_7@
  50. (43 rows)@H_404_7@

运算符类包含哪些运算符

  1. select amop.amopopr::regoperator@H_404_7@
  2. from pg_opclass opc, pg_opfamily opf, pg_am am, pg_amop amop@H_404_7@
  3. where opc.opcname = 'array_ops'@H_404_7@
  4. and opf.oid = opc.opcfamily@H_404_7@
  5. and am.oid = opf.opfmethod@H_404_7@
  6. and amop.amopfamily = opc.opcfamily@H_404_7@
  7. and am.amname = 'btree'@H_404_7@
  8. and amop.amoplefttype = opc.opcintype;@H_404_7@
  9. amopopr @H_404_7@
  10. -----------------------@H_404_7@
  11. <(anyarray,anyarray)@H_404_7@
  12. <=(anyarray,anyarray)@H_404_7@
  13. =(anyarray,anyarray)@H_404_7@
  14. >=(anyarray,anyarray)@H_404_7@
  15. >(anyarray,anyarray)@H_404_7@
  16. (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

索引支持的新数据类型

  1. --创建一个新的组合类型@H_404_7@
  2. create type complex as (re float, im float);@H_404_7@
  3. @H_404_7@
  4. --创建表@H_404_7@
  5. create table t1(x complex);@H_404_7@
  6. insert into t1 values ((0.0, 10.0)), ((1.0, 3.0)), ((1.0, 1.0));@H_404_7@
  7. insert into t1 values((1.0,2.0)),((2.0,2.0));@H_404_7@

认情况,对于组合类型排序是分开的,先比较第一个字段再比较第二个,也可以通过其他方式排序。

  1. --创建相关函数@H_404_7@
  2. create function modulus(a complex) returns float as $$@H_404_7@
  3. select sqrt(a.re*a.re + a.im*a.im);@H_404_7@
  4. $$ immutable language sql;@H_404_7@
  5. @H_404_7@
  6. --定义5种操作符函数:@H_404_7@
  7. create function complex_lt(a complex, b complex) returns boolean as $$@H_404_7@
  8. select modulus(a) < modulus(b);@H_404_7@
  9. $$ immutable language sql;@H_404_7@
  10. @H_404_7@
  11. create function complex_le(a complex, b complex) returns boolean as $$@H_404_7@
  12. select modulus(a) <= modulus(b);@H_404_7@
  13. $$ immutable language sql;@H_404_7@
  14. @H_404_7@
  15. create function complex_eq(a complex, b complex) returns boolean as $$@H_404_7@
  16. select modulus(a) = modulus(b);@H_404_7@
  17. $$ immutable language sql;@H_404_7@
  18. @H_404_7@
  19. create function complex_ge(a complex, b complex) returns boolean as $$@H_404_7@
  20. select modulus(a) >= modulus(b);@H_404_7@
  21. $$ immutable language sql;@H_404_7@
  22. @H_404_7@
  23. create function complex_gt(a complex, b complex) returns boolean as $$@H_404_7@
  24. select modulus(a) > modulus(b);@H_404_7@
  25. $$ immutable language sql;@H_404_7@

创建对应的操作符

  1. create operator #<#(leftarg=complex, rightarg=complex, procedure=complex_lt);@H_404_7@
  2. @H_404_7@
  3. create operator #<=#(leftarg=complex, rightarg=complex, procedure=complex_le);@H_404_7@
  4. @H_404_7@
  5. create operator #=#(leftarg=complex, rightarg=complex, procedure=complex_eq);@H_404_7@
  6. @H_404_7@
  7. create operator #>=#(leftarg=complex, rightarg=complex, procedure=complex_ge);@H_404_7@
  8. @H_404_7@
  9. create operator #>#(leftarg=complex, rightarg=complex, procedure=complex_gt);@H_404_7@
  10. @H_404_7@
  11. --比较数字@H_404_7@
  12. select (1.0,1.0)::complex #<# (1.0,3.0)::complex;@H_404_7@

除了整个5个操作符,还需要定义函数:小于返回-1;等于返回0;大于返回1。其他访问方法可能需要定义其他函数

  1. create function complex_cmp(a complex, b complex) returns integer as $$@H_404_7@
  2. select case when modulus(a) < modulus(b) then -1@H_404_7@
  3. when modulus(a) > modulus(b) then 1@H_404_7@
  4. else 0@H_404_7@
  5. end; $$ language sql;@H_404_7@

创建一个操作符类

  1. create operator class complex_ops@H_404_7@
  2. default for type complex@H_404_7@
  3. using btree as@H_404_7@
  4. operator 1 #<#,@H_404_7@
  5. operator 2 #<=#,@H_404_7@
  6. operator 3 #=#,@H_404_7@
  7. operator 4 #>=#,@H_404_7@
  8. operator 5 #>#,@H_404_7@
  9. function 1 complex_cmp(complex,complex);@H_404_7@
  10. @H_404_7@
  11. --查看排序结构@H_404_7@
  12. mydb=# select * from t1 order by x;@H_404_7@
  13. x @H_404_7@
  14. --------@H_404_7@
  15. (1,1)@H_404_7@
  16. (1,3)@H_404_7@
  17. (0,10)@H_404_7@
  18. (3 rows)@H_404_7@
  19. @H_404_7@
  20. --查看可以使用此查询获取支持函数:@H_404_7@
  21. select amp.amprocnum,@H_404_7@
  22. amp.amproc,@H_404_7@
  23. amp.amproclefttype::regtype,@H_404_7@
  24. amp.amprocrighttype::regtype@H_404_7@
  25. from pg_opfamily opf,@H_404_7@
  26. pg_am am,@H_404_7@
  27. pg_amproc amp@H_404_7@
  28. where opf.opfname = 'complex_ops'@H_404_7@
  29. and opf.opfmethod = am.oid@H_404_7@
  30. and am.amname = 'btree'@H_404_7@
  31. and amp.amprocfamily = opf.oid;@H_404_7@
  32. @H_404_7@
  33. amprocnum | amproc | amproclefttype | amprocrighttype @H_404_7@
  34. -----------+-------------+----------------+-----------------@H_404_7@
  35. 1 | complex_cmp | complex | complex@H_404_7@
  36. (1 row)@H_404_7@

管理操作符

  1. --查看 操作符 和操作符类@H_404_7@
  2. select * from pg_operator;@H_404_7@
  3. select * from pg_opclass;@H_404_7@
  4. @H_404_7@
  5. --查看操作符类型@H_404_7@
  6. select o.oid,o.oprname,@H_404_7@
  7. (select t.typname from pg_type t @H_404_7@
  8. where o.oprleft=t.oid) as oprleft,@H_404_7@
  9. (select t.typname from pg_type t@H_404_7@
  10. where o.oprright=t.oid) as oprright@H_404_7@
  11. from pg_operator o where o.oprname like '#%#';@H_404_7@
  12. @H_404_7@
  13. --删除操作符@H_404_7@
  14. drop operator #<# (complex,complex);@H_404_7@
  15. --删除操作类@H_404_7@
  16. DROP OPERATOR CLASS complex_ops using btree;@H_404_7@
  17. @H_404_7@
  18. --删除函数@H_404_7@
  19. select * from pg_proc where proname like 'com%';@H_404_7@
  20. drop function function_name;@H_404_7@

参考资料

BTREE索引

重要特征

  • B树是平衡的
  • B树是多分支的,即每个页面(通常为8 KB)包含许多(数百个)ctid。因此,B树的深度很小,对于非常大的表,实际上可以达到4–5的深度。
  • 索引中的数据按非递减顺序排序,(在页面之间和每个页面内部),并且同一级别的页面通过双向列表相互连接。因此,我们可以仅通过列表的一个方向或另一个方向获得有序数据集,而不必每次都返回到根。

无论哪种扫描类型(index scan、index only scan、bitmap scan),使用btree索引都会返回有序的数据。所以,如果在排序列上存在索引,优化器会首先考虑是索引扫描,否则就是先顺序扫描然后排序。

  1. create index idx_t1 on t1(c1 desc);@H_404_7@
  2. --尤其组合索引 ,如果常用排序,可使用如下方法@H_404_7@
  3. create index idx_t1 on t1(c1 desc,c2 asc);@H_404_7@

空值

pg索引可以存储空值,并支持按条件IS NULL和IS NOT NULL进行搜索

  1. 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的值去区分.

  1. Meta page @H_404_7@
  2. root page # btpo_flags=2 @H_404_7@
  3. branch page # btpo_flags=0 @H_404_7@
  4. leaf page # btpo_flags=1 @H_404_7@
  5. leaf&root page # btpo_flags=3@H_404_7@
  6. @H_404_7@
  7. --详情见:src/include/access/nbtree.h@H_404_7@
  8. /* Bits defined in btpo_flags */@H_404_7@
  9. #define BTP_LEAF (1 << 0) /* leaf page, i.e. not internal page */@H_404_7@
  10. #define BTP_ROOT (1 << 1) /* root page (has no parent) */@H_404_7@
  11. #define BTP_DELETED (1 << 2) /* page has been deleted from tree */@H_404_7@
  12. #define BTP_Meta (1 << 3) /* Meta-page */@H_404_7@
  13. #define BTP_HALF_DEAD (1 << 4) /* empty, but still in tree */@H_404_7@
  14. #define BTP_SPLIT_END (1 << 5) /* rightmost page of split group */@H_404_7@
  15. #define BTP_HAS_GARBAGE (1 << 6) /* page has LP_DEAD tuples */@H_404_7@
  16. #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

使用场景:

使用限制:

    • 1、不支持对null的处理;
    • 2、不能使用index only scan;
    • 3、不支持多列索引。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐