PostgreSQL码农集散地

PostgreSQL 18 preview - range类型增加GiST 和 B-树的 sortsupport 接口

PostgreSQL 18 preview - range类型增加GiST 和 B-树的 sortsupport 接口

range类型是PostgreSQL的特色数据类型之一, 可以表达同一个类型的一段范围, 例如IP地址段、时间区间、数字区间等.

例子, 使用索引加速, 可以快速判断某个IP是否落在某个IP地址段范围内, 加速智能DNS.

《PostgreSQL 黑科技 range 类型及 gist index 20x+ speedup than Mysql index combine query》

PostgreSQL 18 为范围类型(range type)添加了 GiST 和 B-树的 sortsupport , 加速索引构建, 提升排序性能.

https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=e9e7b66044c9e3dfa76fd1599d5703acd3e4a3f5

Add GiST and btree sortsupport routines for range types  
author Heikki Linnakangas <[email protected]>   
Wed, 2 Apr 2025 16:51:28 +0000 (19:51 +0300)  
committer Heikki Linnakangas <[email protected]>   
Wed, 2 Apr 2025 16:51:28 +0000 (19:51 +0300)  
commit e9e7b66044c9e3dfa76fd1599d5703acd3e4a3f5  
tree 1fa6b61fa306e98cd33471b2e35e5aa439bbe075 tree  
parent ea3f9b6da34a1a4dc2c0c118789587c2a85c78d7 commit | diff  
Add GiST and btree sortsupport routines for range types  

For GiST, having a sortsupport function allows building the index  
using the "sorted build" method, which is much faster.  

For b-tree, the sortsupport routine doesn't give any new  
functionality, but speeds up sorting a tiny bit. The difference is not  
very significant, about 2% in cursory testing on my laptop, because  
the range type comparison function has quite a lot of overhead from  
detoasting. In any case, since we have the function for GiST anyway,  
we might as well register it for the btree opfamily too.  

Author: Bernd Helmle <[email protected]>  
Discussion: https://www.postgresql.org/message-id/[email protected]  

AI 解读

这个补丁为范围类型添加了 GiST 和 B-树的 sortsupport 例程。

背景:

  • GiST (Generalized Search Tree) 索引: GiST 是一种通用的索引访问方法,可以用于各种数据类型和操作符类。
  • B-树索引: B-树是一种常用的索引访问方法,适用于排序数据。
  • sortsupport 例程:sortsupport 例程是 PostgreSQL 中用于优化排序操作的机制。 它允许索引访问方法提供特定的函数,以帮助排序算法更有效地比较和排序数据。

GiST 的改进:

  • 加速索引构建: 对于 GiST 索引,提供 sortsupport 函数允许使用 "sorted build" 方法构建索引。 这种方法比传统的索引构建方法快得多。  "sorted build" 方法通过预先对数据进行排序,然后按排序后的顺序构建索引,从而减少了随机 I/O 操作,提高了构建效率。

B-树的改进:

  • 微小的排序加速: 对于 B-树索引,sortsupport 例程本身并没有提供任何新的功能,但可以稍微提高排序速度。
  • 性能提升有限:  作者测试表明,性能提升并不显著,大约只有 2%。 这是因为范围类型比较函数在比较过程中需要进行 "detoasting" 操作,这会带来相当大的开销。 "detoasting" 是指从存储在磁盘上的压缩或外部格式("toasted")的数据中恢复原始数据的过程。
  • 顺便添加: 尽管 B-树的性能提升有限,但由于已经为 GiST 实现了 sortsupport 函数,因此顺便也将其注册到 B-树操作符族中。

总结:

这个补丁的主要目的是为范围类型的 GiST 索引提供 sortsupport 例程,从而显著加速索引构建过程。 虽然为 B-树索引添加 sortsupport 例程带来的性能提升有限,但由于代码已经存在,因此也将其添加到了 B-树操作符族中。  总的来说,这个补丁通过优化排序操作,提高了范围类型索引的性能。

顺便推广一下5.24 if club上海站活动,欢迎报名