PostgreSQL 创建B-Tree索引的过程

简介: Postgres支持B-tree, hash, GiST, and GIN,也支持用户通过Gist自定义索引方法,比如时空数据库的R-Tree索引。

Postgres支持B-tree, hash, GiST, and GIN,也支持用户通过Gist自定义索引方法,比如时空数据库的R-Tree索引。

为了支持索引框架,在创建索引时会查找和操作一系列Catalog元数据,另外为了加速B-Tree索引的构建,会先对待创建索引的数据进行排序,然后再按照B-Tree的页面格式直接写B-Tree的page,避免page的split。

例子

create table t001(id int, i int, j int, k int, msg text);
create table t002(id int, i int, j int, k int, msg text);
insert into t001 select i, i+1, i+2, i+3, md5(random()::text) from generate_series(1,1000) as i;
insert into t002 select i, i+1, i+2, i+3, md5(random()::text) from generate_series(1,1000) as i;
create index t001_i_j on t001(i, j);

创建B-Tree索引分成2个部分:

  1. catalog系统中生成新索引的相关元数据(索引文件也是一个表,因此相关的元数据需要建立和关联起来);
  2. 对索引列进行排序并生成BTree的page;

校验新索引的Catalog元数据

语法解析

create index t001_i_j on t001 using btree (i, j);

通过parse.y将创建索引的sql解析成IndexStmt结构,其中:

IndexStmt
{
    type = T_IndexStmt
    idxname = "t001_i_j"
    accessMethod = "btree"
}

校验B-Tree的handler

using btree执行了索引的类型是btree,因此需要校验内核是否支持该类型的索引。

pg_am

tuple = SearchSysCache1(AMNAME, PointerGetDatum("btree"));

在pg_am中查找"btree"对应的handler

postgres=# select oid,* from pg_am;
 oid  | amname |  amhandler  | amtype
------+--------+-------------+--------
  403 | btree  | bthandler   | i
  405 | hash   | hashhandler | i
  783 | gist   | gisthandler | i
 2742 | gin    | ginhandler  | i
 4000 | spgist | spghandler  | i
 3580 | brin   | brinhandler | i
(6 行记录)

BTree的handler是bthandler,是一个regproc类型,对应pg_proc一个函数。对于内置的BTree索引,相关的函数是在bootstrap过程中插入(pg_proc.dat文件)。

pg_proc

pg_proc.dat文件(下面代码会被重新格式化成postgres.bki文件,并且在inintdb时被bootstrap.y解析插入):

# Index access method handlers
{ oid => '330', descr => 'btree index access method handler',
  proname => 'bthandler', provolatile => 'v', prorettype => 'index_am_handler',
  proargtypes => 'internal', prosrc => 'bthandler' },
postgres=# select oid,* from pg_proc where proname='bthandler';
-[ RECORD 1 ]---+----------
oid             | 330
proname         | bthandler
pronamespace    | 11
proowner        | 10
prolang         | 12
procost         | 1
prorows         | 0
provariadic     | 0
protransform    | -
prokind         | f
prosecdef       | f
proleakproof    | f
proisstrict     | t
proretset       | f
provolatile     | v
proparallel     | s
pronargs        | 1
pronargdefaults | 0
prorettype      | 325
proargtypes     | 2281
proallargtypes  |
proargmodes     |
proargnames     |
proargdefaults  |
protrftypes     |
prosrc          | bthandler
probin          |
proconfig       |
proacl          |

校验索引列及比较函数

查找pg_attribute,校验create index中指定的索引列是否存在,如果存在记录attno,并且根据atttypid查找对应的比较函数;

校验pg_attribute

postgres=# select a.*  from pg_class c, pg_attribute a  where c.relname='t001' and c.oid = a.attrelid;
-[ RECORD 8 ]-+---------
attrelid      | 16384
attname       | i
atttypid      | 23
attstattarget | -1
attlen        | 4
attnum        | 2
attndims      | 0
attcacheoff   | -1
atttypmod     | -1
attbyval      | t
attstorage    | p
attalign      | i
attnotnull    | f
atthasdef     | f
atthasmissing | f
attidentity   |
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 0
attacl        |
attoptions    |
attfdwoptions |
attmissingval |
-[ RECORD 9 ]-+---------
attrelid      | 16384
attname       | j
atttypid      | 23
attstattarget | -1
attlen        | 4
attnum        | 3
attndims      | 0
attcacheoff   | -1
atttypmod     | -1
attbyval      | t
attstorage    | p
attalign      | i
attnotnull    | f
atthasdef     | f
atthasmissing | f
attidentity   |
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 0
attacl        |
attoptions    |
attfdwoptions |
attmissingval |

查找比较函数

其中403是pg_am中btree的handler的oid

postgres=# select * from pg_opclass where  opcmethod = 403 and opcintype  = 23;
-[ RECORD 1 ]+---------
opcmethod    | 403
opcname      | int4_ops
opcnamespace | 11
opcowner     | 10
opcfamily    | 1976
opcintype    | 23
opcdefault   | t
opckeytype   | 0

在经过上述元数据校验之后,可以开始为新的索引文件生成相关元数据了。

创建新索引的元数据

在文件系统中创建索引文件

生成Oid

DefineIndex -> index_create -> GetNewRelFileNode

为新的索引文件生成唯一oid,过程是:生成一个新的oid,然后查找pg_class的索引,如果不存在就返回这个oid。

跟新本地的relcache

把正在创建的relation添加到relcache系统中

DefineIndex -> index_create -> heap_create -> RelationBuildLocalRelation

创建文件

DefineIndex -> index_create -> heap_create -> RelationCreateStorage
  1. 文件系统中生成新的文件;
路径:
 "file-dio:///home/postgres/tmp_datadir_polardb_pg_1100_bld/base/13881/16391"
  1. 生成wal日志,类型是
XLogInsert(RM_SMGR_ID, XLOG_SMGR_CREATE | XLR_SPECIAL_REL_UPDATE)

创建新索引的Catalog元数据

pg_class

新的索引文件也是一个表文件,因此需要插入到pg_class中:

DefineIndex -> index_create -> InsertPgClassTuple
postgres=# select * from pg_class where relname = 't001_i_j';
-[ RECORD 1 ]-------+---------
relname             | t001_i_j
relnamespace        | 2200
reltype             | 0
reloftype           | 0
relowner            | 10
relam               | 403
relfilenode         | 16396
reltablespace       | 0
relpages            | 6
reltuples           | 1100
relallvisible       | 0
reltoastrelid       | 0
relhasindex         | f
relisshared         | f
relpersistence      | p
relkind             | i
relnatts            | 2
relchecks           | 0
relhasoids          | f
relhasrules         | f
relhastriggers      | f
relhassubclass      | f
relrowsecurity      | f
relforcerowsecurity | f
relispopulated      | t
relreplident        | n
relispartition      | f
relrewrite          | 0
relfrozenxid        | 0
relminmxid          | 0
relacl              |
reloptions          |

pg_attribute

把索引文件引用的列插入pg_attr中:

DefineIndex -> index_create -> AppendAttributeTuples
postgres=# select a.*  from pg_class c, pg_attribute a  where c.relname='t001_i_j' and c.oid = a.attrelid;
-[ RECORD 1 ]-+------
attrelid      | 16396
attname       | i
atttypid      | 23
attstattarget | -1
attlen        | 4
attnum        | 1
attndims      | 0
attcacheoff   | -1
atttypmod     | -1
attbyval      | t
attstorage    | p
attalign      | i
attnotnull    | f
atthasdef     | f
atthasmissing | f
attidentity   |
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 0
attacl        |
attoptions    |
attfdwoptions |
attmissingval |
-[ RECORD 2 ]-+------
attrelid      | 16396
attname       | j
atttypid      | 23
attstattarget | -1
attlen        | 4
attnum        | 2
attndims      | 0
attcacheoff   | -1
atttypmod     | -1
attbyval      | t
attstorage    | p
attalign      | i
attnotnull    | f
atthasdef     | f
atthasmissing | f
attidentity   |
attisdropped  | f
attislocal    | t
attinhcount   | 0
attcollation  | 0
attacl        |
attoptions    |
attfdwoptions |
attmissingval |
postgres=#

pg_index

把索引本身相关信息插入pg_index中,如果索引包含了表达式,则把表达式通过nodeToString序列化成字符串:

DefineIndex -> index_create -> UpdateIndexRelation
postgres=# select * from pg_indexes where indexname = 't001_i_j';
-[ RECORD 1 ]-------------------------------------------------------
schemaname | public
tablename  | t001
indexname  | t001_i_j
tablespace |
indexdef   | CREATE INDEX t001_i_j ON public.t001 USING btree (i, j)
postgres=#

relcache生效

为了使catalog元数据的变更对所有进程生效,把该heap相关的元数据invalid掉,此处仅仅是注册失效函数,在CommandCounterIncrement,开启执行下一个command时才真正执行invalid。

DefineIndex -> index_create -> CacheInvalidateRelcache

pg_depend

记录该索引对heap的依赖,对collations的依赖,对opclass的依赖,

比如:
t001_i_j依赖表 t001的i;
t001_i_j依赖表 t001的j;
postgres=# select * from pg_depend where objid = 16396;
-[ RECORD 1 ]------
classid     | 1259
objid       | 16396
objsubid    | 0
refclassid  | 1259
refobjid    | 16384
refobjsubid | 2
deptype     | a
-[ RECORD 2 ]------
classid     | 1259
objid       | 16396
objsubid    | 0
refclassid  | 1259
refobjid    | 16384
refobjsubid | 3
deptype     | a

CommandCounterIncrement

使得新索引文件相关的relcache生效

构建B-Tree索引

create index时通过"btree" ,找到bthandler函数,找到btbuild

DefineIndex -> index_create -> index_build -> btbuild

排序

构建sortkey

通过index的索引列构建排序时需要用到的sortkey:

btbuild -> _bt_spools_heapscan -> tuplesort_begin_index_btree

扫描heap表

在非concurrent模式下create index时,为了扫描所有的tpule,snapshot使用SnapshotAny,

btbuild -> _bt_spools_heapscan -> IndexBuildHeapScan -> IndexBuildHeapRangeScan -> heap_getnext

自下向上构建B-Tree索引page

逐个读取排好序的tuple,填充到B-Tree的叶子节点上,自下向上插入B-Tree,插入叶子节点可能会递归的触发起父节点也插入。

page layout

索引页面的内存布局整体上是遵循堆表的布局:pageheader,行指针数组构成。

不同点是:

1. 页面的尾巴上多了BTree自定义的BTPageOpaqueData结构,和左右邻居页面组织成链表;

2. 每个行指针指向的内容由IndexTupleData和key组成;

image.png

填充率

向刚刚创建出来的索引插入新的数据时,为了避免split,在第一次构建索引时,每个页面上都预留了一些空间:

1. 叶子节点90%;

2. 中间节点70%;

自下向上构建

  1. 填充叶子page:leaf-0;
  2. 当leaf-0满了,leaf-0落盘前需要把它的邻居和父节点相关指针更新;
  3. 分配一个paret0,leaf-0插入parent0中;
  4. 分配一个新的页面leaf-1,leaf-0的右指针指向leaf-1;
  5. leaft-0可以落盘;
  6. leaft-1也满了后,过程和2到6一样;
  7. 当leaf-2满了后,要把leaf-2插入父节点,此时父节点也满了,因此要递归的把父节点落盘,过程和2到6一样;

leaf-0

image.png

leaf-0满了

image.png

leaf-1满了

image.png

leaf-2满了,先递归处理parent0满的情况

image.png

leaf-2满了,再处理leaf-2自身满的情况

image.png

indextuple和scankey的语义

  1. 对于叶子节点,indextuple指向heap表的行指针;
  2. 对于中间节点,indextuple指向大于scankey的页面,是一个左闭右开区间[scankey, );

索引页面中真正存放的是indextuple和scankey的组合,在page这个层面中把这两个当做一个item,长度是两者之和;

在实际查找时,同时linp定位到indextuple,由于indextuple是定长的,只需要再往前移动sizeof(indextuple)就能找到scankey的datum和null区域;

根据index的attribute desc来解析datum和null;

key space

image.png

对于-Tree中间节点的任意一层,它的所有的indextuple和scankey并集在一起是[负无穷,正无穷]。

由于一对indextuple和scankey组合表达的是左闭右开区间[scankey, ):

1. 对于最右侧的scankey (k4),它的语义本身就是[scankey,正无穷);

2. 对于最左侧的scankey (k1),这个key本身代表的是负无穷的语义:

使用该层出现的第一个key内容(记录在pagesate->minkey);

indextuple中只记录blkno,使用offset来记录attr为0;

不存储scankey的datum和null;

if (last_off == P_HIKEY)
    {
        Assert(state->btps_minkey == NULL);
        state->btps_minkey = CopyIndexTuple(itup);
        BTreeTupleSetNAtts(state->btps_minkey, 0);
    }
    ...
    if (!P_ISLEAF(opaque) && itup_off == P_FIRSTKEY)
    {
        trunctuple = *itup;
        trunctuple.t_info = sizeof(IndexTupleData);
        BTreeTupleSetNAtts(&trunctuple, 0);
        itup = &trunctuple;
        itemsize = sizeof(IndexTupleData); //大小仅仅是indextuple,去除了datum和null
    }

high key和first key

image.png

每个非最右侧页面都有highkey,highkey的语义是改页面所有key的上界(不包含),因此最右侧页面没有highkey,它的上界是正无穷。

页面1的highkey是在页面1满了之后,生成页面2时确定下来的:

1. 把页面1的highkey内容拷贝到页面2,做为页面2的FIRSTKEY;

2. 设置页面1的P_HIHEY指向最后一个行指针last_off,并且标记last_off为无效指针;

因此,页面1的highkey是页面2的FIRSTKEY。

未满页面的落盘

image.png

当所有的heap表都被插入了之后,还没有达到满的页面需要落盘,在自下向上的过程中,插入父节点时是一个递归的过程,为了维护每次递归的状态信息,每层的页面用一个BTPageState结构来描述:

  1. 记录level;
  2. 记录当前层的最右侧的page;
  3. 记录minkey;

BTPageState结构是一个单向链表,因此在插入了所有heap表之后,只需要遍历这个链表,从叶子节点开始落盘。

注意:过程中会往往父节点插入(indextuple,scankey),可能会触发父节点满了而落盘,因而产生一个新的父节点,所属层的BTPageState会被更新,沿着BTPageState链表会最终把这个新产生的页面也落盘了。

metapage

metapage记录B-Tree:level,root,fastroot等信息。

metapge始终在索引文件的第0个page,root的位置是不固定的。

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍如何基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
相关文章
|
8月前
|
存储 SQL 关系型数据库
mysql底层原理:索引、慢查询、 sql优化、事务、隔离级别、MVCC、redolog、undolog(图解+秒懂+史上最全)
mysql底层原理:索引、慢查询、 sql优化、事务、隔离级别、MVCC、redolog、undolog(图解+秒懂+史上最全)
mysql底层原理:索引、慢查询、 sql优化、事务、隔离级别、MVCC、redolog、undolog(图解+秒懂+史上最全)
|
8月前
|
存储 关系型数据库 MySQL
MySQL数据库索引的数据结构?
MySQL中默认使用B+tree索引,它是一种多路平衡搜索树,具有树高较低、检索速度快的特点。所有数据存储在叶子节点,非叶子节点仅作索引,且叶子节点形成双向链表,便于区间查询。
233 4
|
10月前
|
存储 关系型数据库 MySQL
阿里面试:MySQL 一个表最多 加几个索引? 6个?64个?还是多少?
阿里面试:MySQL 一个表最多 加几个索引? 6个?64个?还是多少?
阿里面试:MySQL 一个表最多 加几个索引? 6个?64个?还是多少?
|
9月前
|
存储 监控 关系型数据库
B-tree不是万能药:PostgreSQL索引失效的7种高频场景与破解方案
在PostgreSQL优化实践中,B-tree索引虽承担了80%以上的查询加速任务,但因多种原因可能导致索引失效,引发性能骤降。本文深入剖析7种高频失效场景,包括隐式类型转换、函数包裹列、前导通配符等,并通过实战案例揭示问题本质,提供生产验证的解决方案。同时,总结索引使用决策矩阵与关键原则,助你让索引真正发挥作用。
577 0
|
关系型数据库 MySQL 数据库
Mysql的索引
MYSQL索引主要有 : 单列索引 , 组合索引和空间索引 , 用的比较多的就是单列索引和组合索引 , 空间索引我这边没有用到过 单列索引 : 在MYSQL数据库表的某一列上面创建的索引叫单列索引 , 单列索引又分为 ● 普通索引:MySQL中基本索引类型,没有什么限制,允许在定义索引的列中插入重复值和空值,纯粹为了查询数据更快一点。 ● 唯一索引:索引列中的值必须是唯一的,但是允许为空值 ● 主键索引:是一种特殊的唯一索引,不允许有空值 ● 全文索引: 只有在MyISAM引擎、InnoDB(5.6以后)上才能使⽤用,而且只能在CHAR,VARCHAR,TEXT类型字段上使⽤用全⽂文索引。
|
SQL 关系型数据库 MySQL
深入解析MySQL的EXPLAIN:指标详解与索引优化
MySQL 中的 `EXPLAIN` 语句用于分析和优化 SQL 查询,帮助你了解查询优化器的执行计划。本文详细介绍了 `EXPLAIN` 输出的各项指标,如 `id`、`select_type`、`table`、`type`、`key` 等,并提供了如何利用这些指标优化索引结构和 SQL 语句的具体方法。通过实战案例,展示了如何通过创建合适索引和调整查询语句来提升查询性能。
3121 10
|
8月前
|
存储 SQL 关系型数据库
MySQL 核心知识与索引优化全解析
本文系统梳理了 MySQL 的核心知识与索引优化策略。在基础概念部分,阐述了 char 与 varchar 在存储方式和性能上的差异,以及事务的 ACID 特性、并发事务问题及对应的隔离级别(MySQL 默认 REPEATABLE READ)。 索引基础部分,详解了 InnoDB 默认的 B+tree 索引结构(多路平衡树、叶子节点存数据、双向链表支持区间查询),区分了聚簇索引(数据与索引共存,唯一)和二级索引(数据与索引分离,多个),解释了回表查询的概念及优化方法,并分析了 B+tree 作为索引结构的优势(树高低、效率稳、支持区间查询)。 索引优化部分,列出了索引创建的六大原则
203 2
|
9月前
|
存储 关系型数据库 MySQL
MySQL覆盖索引解释
总之,覆盖索引就像是图书馆中那些使得搜索变得极为迅速和简单的工具,一旦正确使用,就会让你的数据库查询飞快而轻便。让数据检索就像是读者在图书目录中以最快速度找到所需信息一样简便。这样的效率和速度,让覆盖索引成为数据库优化师傅们手中的尚方宝剑,既能够提升性能,又能够保持系统的整洁高效。
297 9
|
10月前
|
机器学习/深度学习 关系型数据库 MySQL
对比MySQL全文索引与常规索引的互异性
现在,你或许明白了这两种索引的差异,但任何技术决策都不应仅仅基于理论之上。你可以创建你的数据库实验环境,尝试不同类型的索引,看看它们如何影响性能,感受它们真实的力量。只有这样,你才能熟悉它们,掌握什么时候使用全文索引,什么时候使用常规索引,以适应复杂多变的业务需求。
264 12
|
存储 关系型数据库 MySQL
MySQL索引学习笔记
本文深入探讨了MySQL数据库中慢查询分析的关键概念和技术手段。
834 81

推荐镜像

更多