数据库

HypoPG: 假设性索引


HypoPG 是 PostgreSQL 的一个扩展,用于创建假设/虚拟索引。HypoPG 允许用户快速创建对 Postgres 查询规划器可见的假设/虚拟索引,这些索引不会消耗任何服务器资源(CPU、磁盘、内存)。

HypoPG 的设计初衷是让用户能够在不消耗服务器资源或等待索引构建的情况下,快速寻找能改善慢查询的索引方案。

启用扩展

  1. 进入 Dashboard 的数据库页面
  2. 在侧边栏点击 Extensions
  3. 搜索 hypopg 并启用该扩展

加速查询性能

给定以下表格和一个通过id从表中查询数据的简单SQL语句:

1
2
3
4
5
6
7
8
9
10
11
create table account ( id int, address text);insert into account(id, address)select id, id || ' main street'from generate_series(1, 10000) id;

我们可以生成执行计划(explain plan)来了解Postgres查询规划器打算如何执行该查询。

1
2
3
4
5
6
7
explain select * from account where id=1; QUERY PLAN------------------------------------------------------- Seq Scan on account (cost=0.00..180.00 rows=1 width=13) Filter: (id = 1)(2 rows)

使用HypoPG扩展,我们可以在account(id)列上创建一个假设性索引,检查它是否对查询规划器有帮助,然后重新生成执行计划。

请注意,HypoPG创建的虚拟索引仅在创建它们的Postgres连接中可见。Supabase通过连接池连接到Postgres,因此hypopg_create_index语句和explain语句应该在同一个查询中执行。

1
2
3
4
5
6
7
8
9
select * from hypopg_create_index('create index on account(id)');explain select * from account where id=1; QUERY PLAN------------------------------------------------------------------------------------ Index Scan using <13504>btree_account_id on hypo (cost=0.29..8.30 rows=1 width=13) Index Cond: (id = 1)(2 rows)

执行计划已从Seq Scan(顺序扫描)变更为使用新创建的虚拟索引进行Index Scan(索引扫描),因此我们可以选择创建真实的索引来提升目标查询的性能:

1
create index on account(id);

函数

相关资源