当前位置:   article > 正文

POSTGRESQL (PG) 6种索引类型介绍以及使用实例_postgresql 索引类型

postgresql 索引类型

数据库SQL查询优化中,索引是最常用的优化手段。合理的使用索引,可以极大提升数据库查询效率,充分利用系统资源。数据库中,数据选择率比较低的时候使用索引可以带来性能提升,但是如果数据选择率比较高,索引额外带来索引读代价,同时会带来随机读的问题,性能不如顺序扫描。因此本文介绍的索引类型只能用于数据选择率比较低的SQL语句。这是选择索引的前提。

Postgresql中主要支持6种类型的索引:BTREE、HASH、GiST、SP-GiSP、GIN、BRIN。可以根据实际的应用场景选择合适的索引,BTREE、HASH是比较常用的索引。

1. BTREE索引:

CREATE INDEX默认使用BTREE索引,适合按照顺序存储的数据进行比较查询和范围查询,查询优化器会优先考虑使用BTREE索引,如果涉及到以下任何一种操作:

1)<,<=,=,>,>=

2)以及这些操作的组合,比如between and,也可以使用BTREE。

3)在索引列上的IS NULL 或者IS NOT NULL也可以使用BTREE。

4)BTREE索引也可以用于模糊查询,但是仅限字符串开头是常量的情况下,比如 name LIKE ‘Jason%’,或者name ~ ’^Jason’。但是name LIKE ‘%Jason’是不能用的。

5)Min/Max聚集操作也可使用BTREE索引。

6)其实在merge join以及order by中,可以通过使用BTREE索引的有序性来减少sort带来的代价。

例子:

  1. test=# create table t1 (id int, info text);
  2. CREATE TABLE
  3. test=# insert into t1 values(generate_series(1,100000), md5(random()::text));
  4. INSERT 0 100000
  5. test=# \d t1
  6. Table "public.t1"
  7. Column | Type | Collation | Nullable | Default
  8. --------+---------+-----------+----------+---------
  9. id | integer | | |
  10. info | text | | |
  11. test=# analyze t1;
  12. ANALYZE
  13. --不建立索引,默认使用顺序扫描
  14. test=# explain select * from t1 where t1.id = 10007;
  15. QUERY PLAN
  16. ------------------------------------------------------
  17. Seq Scan on t1 (cost=0.00..2084.00 rows=1 width=37)
  18. Filter: (id = 10007)
  19. (2 rows)
  20. test=# explain select * from t1 where t1.id >10007;
  21. QUERY PLAN
  22. ----------------------------------------------------------
  23. Seq Scan on t1 (cost=0.00..2084.00 rows=90249 width=37)
  24. Filter: (id > 10007)
  25. (2 rows)
  26. test=# explain select * from t1 where t1.id > 10007 and t1.id < 12000;
  27. QUERY PLAN
  28. ---------------------------------------------------------
  29. Seq Scan on t1 (cost=0.00..2334.00 rows=2042 width=37)
  30. Filter: ((id > 10007) AND (id < 12000))
  31. (2 rows)
  32. --建立BTREE索引
  33. test=# create index on t1(id);
  34. CREATE INDEX
  35. test=# analyze t1;
  36. ANALYZE
  37. test=# explain select * from t1 where t1.id = 10007;
  38. QUERY PLAN
  39. ---------------------------------------------------------------------
  40. Index Scan using t1_id_idx on t1 (cost=0.29..8.31 rows=1 width=37)
  41. Index Cond: (id = 10007)
  42. (2 rows)
  43. --下面例子中没有使用索引的原因是选择率太高,优化器会使用顺序扫描
  44. test=# explain select * from t1 where t1.id >10007;
  45. QUERY PLAN
  46. ----------------------------------------------------------
  47. Seq Scan on t1 (cost=0.00..2084.00 rows=90103 width=37)
  48. Filter: (id > 10007)
  49. (2 rows)
  50. test=# explain select * from t1 where t1.id > 10007 and t1.id < 12000;
  51. QUERY PLAN
  52. -------------------------------------------------------------------------
  53. Index Scan using t1_id_idx on t1 (cost=0.29..83.73 rows=1972 width=37)
  54. Index Cond: ((id > 10007) AND (id < 12000))
  55. (2 rows)
  56. test=# explain select * from t1 where t1.id >98765;
  57. QUERY PLAN
  58. -------------------------------------------------------------------------
  59. Index Scan using t1_id_idx on t1 (cost=0.29..51.31 rows=1201 width=37)
  60. Index Cond: (id > 98765)
  61. (2 rows)
  62. test=# \d t1
  63. Table "public.t1"
  64. Column | Type | Collation | Nullable | Default
  65. --------+---------+-----------+----------+---------
  66. id | integer | | |
  67. info | text | | |
  68. Indexes:
  69. "t1_id_idx" btree (id)
  70. test=# explain select * from t1 where t1.id between 10007 and 11000;
  71. QUERY PLAN
  72. ------------------------------------------------------------------------
  73. Index Scan using t1_id_idx on t1 (cost=0.29..43.79 rows=975 width=37)
  74. Index Cond: ((id >= 10007) AND (id <= 11000))
  75. (2 rows)
  76. test=# explain select * from t1 where t1.id IS NULL;
  77. QUERY PLAN
  78. ---------------------------------------------------------------------
  79. Index Scan using t1_id_idx on t1 (cost=0.29..4.31 rows=1 width=37)
  80. Index Cond: (id IS NULL)
  81. (2 rows)
  82. test=# create index on t1(info text_pattern_ops);
  83. CREATE INDEX
  84. test=# \d t1;
  85. Table "public.t1"
  86. Column | Type | Collation | Nullable | Default
  87. --------+---------+-----------+----------+---------
  88. id | integer | | |
  89. info | text | | |
  90. Indexes:
  91. "t1_id_idx" btree (id)
  92. "t1_info_idx" btree (info text_pattern_ops)
  93. test=# analyze t1;
  94. ANALYZE
  95. --模糊查询使用索引
  96. test=# explain select * from t1 where t1.info like '0123%';
  97. QUERY PLAN
  98. ------------------------------------------------------------------------
  99. Index Scan using t1_info_idx on t1 (cost=0.42..8.44 rows=10 width=37)
  100. Index Cond: ((info ~>=~ '0123'::text) AND (info ~<~ '0124'::text))
  101. Filter: (info ~~ '0123%'::text)
  102. (3 rows)
  103. test=# explain analyze select min(id) from t1;
  104. QUERY PLAN
  105. -----------------------------------------------------------------------------------------------------------------------------------------
  106. Result (cost=0.33..0.34 rows=1 width=4) (actual time=0.143..0.143 rows=1 loops=1)
  107. InitPlan 1 (returns $0)
  108. -> Limit (cost=0.29..0.33 rows=1 width=4) (actual time=0.114..0.116 rows=1 loops=1)
  109. -> Index Only Scan using t1_id_idx on t1 (cost=0.29..3691.29 rows=100000 width=4) (actual time=0.107..0.107 rows=1 loops=1)
  110. Index Cond: (id IS NOT NULL)
  111. Heap Fetches: 1
  112. Planning Time: 0.531 ms
  113. Execution Time: 0.263 ms
  114. (8 rows)
  115. test=# explain analyze select max(id) from t1;
  116. QUERY PLAN
  117. --------------------------------------------------------------------------------------------------------------------------------------------------
  118. Result (cost=0.33..0.34 rows=1 width=4) (actual time=0.054..0.054 rows=1 loops=1)
  119. InitPlan 1 (returns $0)
  120. -> Limit (cost=0.29..0.33 rows=1 width=4) (actual time=0.043..0.044 rows=1 loops=1)
  121. -> Index Only Scan Backward using t1_id_idx on t1 (cost=0.29..3691.29 rows=100000 width=4) (actual time=0.040..0.041 rows=1 loops=1)
  122. Index Cond: (id IS NOT NULL)
  123. Heap Fetches: 1
  124. Planning Time: 0.485 ms
  125. Execution Time: 0.128 ms
  126. (8 rows)
  127. test=#

2. Hash索引:

只能处理简单的等值比较,当索引列涉及到等于操作比较时,优化器会考虑使用Hash索引。Hash索引是通过比较hash值来查找定位,如果hash索引列的数据重复度比较高,容易产生严重的hash冲突,从而降低查询效率,因此这种情况下,不适合hash索引。

CREATE INDEX idx_name ON table_name USING HASH (column_name);

例子:

  1. test=# create table t2 (id int, info text);
  2. CREATE TABLE
  3. test=# insert into t2 values(generate_series(1,100000), md5(random()::text));
  4. INSERT 0 100000
  5. test=# create index on t2 using hash(id);
  6. CREATE INDEX
  7. test=# analyze t2;
  8. ANALYZE
  9. test=# \d t2;
  10. Table "public.t2"
  11. Column | Type | Collation | Nullable | Default
  12. --------+---------+-----------+----------+---------
  13. id | integer | | |
  14. info | text | | |
  15. Indexes:
  16. "t2_id_idx" hash (id)
  17. test=# explain select * from t2 where id = 10008;
  18. QUERY PLAN
  19. ---------------------------------------------------------------------
  20. Index Scan using t2_id_idx on t2 (cost=0.00..8.02 rows=1 width=37)
  21. Index Cond: (id = 10008)
  22. (2 rows)
  23. --非等于操作不会用到hash索引
  24. test=# explain select * from t2 where id < 10008;
  25. QUERY PLAN
  26. ---------------------------------------------------------
  27. Seq Scan on t2 (cost=0.00..2084.00 rows=9826 width=37)
  28. Filter: (id < 10008)
  29. (2 rows)
  30. test=# explain select * from t2 where id is NULL;
  31. QUERY PLAN
  32. ------------------------------------------------------
  33. Seq Scan on t2 (cost=0.00..1834.00 rows=1 width=37)
  34. Filter: (id IS NULL)
  35. (2 rows)
  36. test=#

3. GiST索引

不是独立的索引类型,是一种架构或者索引模板,是一棵平衡二叉树。适用于多维数据类型和集合数据类型,和Btree索引类似,同样适用于其他的数据类型。GiST可以用来做位置搜索,如包含、相交、左边、右边等。和Btree索引相比,GiST多字段索引在查询条件中包含索引字段的任何子集都会使用索引扫描,而Btree索引只有查询条件包含第一个索引字段才会使用索引扫描。GiST索引特定操作符类型高度依赖于索引策略(操作符类)。GiST跟Btree索引相比,索引创建耗时较长,占用空间也比较大。

下面例子中建立了BTREE组合索引(a, b),如果SQL where条件中有a或者a,b都可以使用该组合索引,但是如果where条件中只有b,则无法使用索引。此时,GiST可以解决这种情况。

例子:

  1. test=# create table t3(a bigint, b timestamp without time zone,c varchar(64));
  2. CREATE TABLE ^
  3. test=# insert into t3 values(generate_series(1,100000), now()::timestamp, md5(random()::text));
  4. INSERT 0 100000
  5. test=# create index on t3(a, b);
  6. CREATE INDEX
  7. test=# analyze t3;
  8. ANALYZE
  9. test=# \d t3
  10. Table "public.t3"
  11. Column | Type | Collation | Nullable | Default
  12. --------+-----------------------------+-----------+----------+---------
  13. a | bigint | | |
  14. b | timestamp without time zone | | |
  15. c | character varying(64) | | |
  16. Indexes:
  17. "t3_a_b_idx" btree (a, b)
  18. test=# explain select * from t3 where a = 10000;
  19. QUERY PLAN
  20. ----------------------------------------------------------------------
  21. Index Scan using t3_a_b_idx on t3 (cost=0.42..8.44 rows=1 width=49)
  22. Index Cond: (a = 10000)
  23. (2 rows)
  24. test=# explain select * from t3 where b = '2022-11-18 17:50:29.245683';
  25. QUERY PLAN
  26. ---------------------------------------------------------------------------
  27. Seq Scan on t3 (cost=0.00..2281.00 rows=1 width=49)
  28. Filter: (b = '2022-11-18 17:50:29.245683'::timestamp without time zone)
  29. (2 rows)
  30. test=# create extension btree_gist;
  31. CREATE EXTENSION
  32. test=# create index idx_t3_gist on t3 using gist(a,b);
  33. CREATE INDEX
  34. test=# analyze t3;
  35. ANALYZE
  36. test=# explain select * from t3 where a = 10000;
  37. QUERY PLAN
  38. ----------------------------------------------------------------------
  39. Index Scan using t3_a_b_idx on t3 (cost=0.42..8.44 rows=1 width=49)
  40. Index Cond: (a = 10000)
  41. (2 rows)
  42. test=# explain select * from t3 where b = '2022-11-18 17:50:29.245683';
  43. QUERY PLAN
  44. -------------------------------------------------------------------------------
  45. Index Scan using idx_t3_gist on t3 (cost=0.28..8.30 rows=1 width=49)
  46. Index Cond: (b = '2022-11-18 17:50:29.245683'::timestamp without time zone)
  47. (2 rows)
  48. test=# explain select * from t3 where a = '10000';
  49. QUERY PLAN
  50. -----------------------------------------------------------------------
  51. Index Scan using idx_t3_gist on t3 (cost=0.28..8.30 rows=1 width=49)
  52. Index Cond: (a = '10000'::bigint)
  53. (2 rows)
  54. test=# explain select * from t3 where a = '10000' or b = '2022-11-18 17:50:29.245683';
  55. QUERY PLAN
  56. ------------------------------------------------------------------------------------------------------------
  57. Bitmap Heap Scan on t3 (cost=8.58..12.59 rows=1 width=49)
  58. Recheck Cond: ((a = '10000'::bigint) OR (b = '2022-11-18 17:50:29.245683'::timestamp without time zone))
  59. -> BitmapOr (cost=8.58..8.58 rows=1 width=0)
  60. -> Bitmap Index Scan on idx_t3_gist (cost=0.00..4.29 rows=1 width=0)
  61. Index Cond: (a = '10000'::bigint)
  62. -> Bitmap Index Scan on idx_t3_gist (cost=0.00..4.29 rows=1 width=0)
  63. Index Cond: (b = '2022-11-18 17:50:29.245683'::timestamp without time zone)
  64. (7 rows)
  65. test=# explain select * from t3 where a = '10000' and b = '2022-11-18 17:50:29.245683';
  66. QUERY PLAN
  67. -----------------------------------------------------------------------------------------------------------
  68. Index Scan using t3_a_b_idx on t3 (cost=0.42..6.19 rows=1 width=49)
  69. Index Cond: ((a = '10000'::bigint) AND (b = '2022-11-18 17:50:29.245683'::timestamp without time zone))
  70. (2 rows)
  71. test=#

4. SP-GiST索引

和GiST类似,但是是一棵不平衡树,支持多维和海量数据,把空间分割成互不相交的部分。SP-GiST适用于空间可以递归分割成不相交区域的结构,包括四叉树、k-D树和基数树。

5. GIN索引

倒排序索引,适合于包含多个组成值的数据,比如数组,全文检索等。用来保存一个键值对的集合,支持用户定义的索引策略,对于不同的索引策略,可以使用不同的操作符。

键值对(Key,postion list):其中Key是一个键值,而postion list是包含Key的位置值。比如('Bob','10:25 14:3 29:5') 就表示关键字'Bob'在这些位置(元组TID)上存在。 当我们用关键字'Bob'去查询的时候,一下就定位到包含关键字的元组有这三个。

使用方法如下:

  1. test=# create table t4(id int, info text);
  2. CREATE TABLE
  3. test=# insert into t4 values(generate_series(1,10000), md5(random()::text));
  4. INSERT 0 10000
  5. test=# create index idx_t4_gin on t4 using gin(to_tsvector('english',info));
  6. CREATE INDEX
  7. test=# analyze t4;
  8. ANALYZE
  9. test=# \d t4
  10. Table "public.t4"
  11. Column | Type | Collation | Nullable | Default
  12. --------+---------+-----------+----------+---------
  13. id | integer | | |
  14. info | text | | |
  15. Indexes:
  16. "idx_t4_gin" gin (to_tsvector('english'::regconfig, info))
  17. test=# explain select * from t4 where to_tsvector('english', info) @@ plainto_tsquery( 'hello');
  18. QUERY PLAN
  19. -------------------------------------------------------------------------------------------------
  20. Bitmap Heap Scan on t4 (cost=12.25..16.77 rows=1 width=37)
  21. Recheck Cond: (to_tsvector('english'::regconfig, info) @@ plainto_tsquery('hello'::text))
  22. -> Bitmap Index Scan on idx_t4_gin (cost=0.00..12.25 rows=1 width=0)
  23. Index Cond: (to_tsvector('english'::regconfig, info) @@ plainto_tsquery('hello'::text))
  24. (4 rows)

6. BRIN索引

块范围索引,它将数据在磁盘上的block按照一定的数目进行分组,分组之后,计算每组的取值范围。在查找数据时,会遍历这些取值范围,排除掉不在范围之内的分组。BRIN索引适用于存储流式数据日志。例如:按照时间插入的数据,由于数据是按照时间插入,因此数据块上记录的范围信息很少会出现交叉情况,索引过滤后需要比较的数据块也会少很多;反之,如果数据交叉严重,通过索引无法过滤掉任何一个数据块时,操作起来会比全表扫描更加耗时。

  1. test=# create table t5(id int, name text);
  2. CREATE TABLE
  3. test=# insert into t5 values(generate_series(1,100000), md5(random()::text));
  4. INSERT 0 100000
  5. test=# create index idx_t5_brin on t5 using brin(id);
  6. CREATE INDEX
  7. test=# analyze t5;
  8. ANALYZE
  9. test=# \d t5
  10. Table "public.t5"
  11. Column | Type | Collation | Nullable | Default
  12. --------+---------+-----------+----------+---------
  13. id | integer | | |
  14. name | text | | |
  15. Indexes:
  16. "idx_t5_brin" brin (id)
  17. test=# explain select * from t5 where id > 98765;
  18. QUERY PLAN
  19. -------------------------------------------------------------------------------
  20. Bitmap Heap Scan on t5 (cost=12.33..1024.91 rows=1199 width=37)
  21. Recheck Cond: (id > 98765)
  22. -> Bitmap Index Scan on idx_t5_brin (cost=0.00..12.03 rows=14286 width=0)
  23. Index Cond: (id > 98765)
  24. (4 rows)
  25. test=# explain analyze select * from t5 where id > 98765;
  26. QUERY PLAN
  27. ----------------------------------------------------------------------------------------------------------------------------
  28. Bitmap Heap Scan on t5 (cost=12.33..1024.91 rows=1199 width=37) (actual time=2.033..2.408 rows=1235 loops=1)
  29. Recheck Cond: (id > 98765)
  30. Rows Removed by Index Recheck: 6605
  31. Heap Blocks: lossy=66
  32. -> Bitmap Index Scan on idx_t5_brin (cost=0.00..12.03 rows=14286 width=0) (actual time=0.043..0.043 rows=1280 loops=1)
  33. Index Cond: (id > 98765)
  34. Planning Time: 0.115 ms
  35. Execution Time: 2.545 ms
  36. (8 rows)
  37. test=#

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/689990
推荐阅读
相关标签
  

闽ICP备14008679号