数据库

HypoPG:假设索引


HypoPG 是 Postgres 扩展,用于创建假设/虚拟索引。HypoPG 允许用户快速创建假设/虚拟索引,这些索引不会产生资源消耗(CPU、磁盘、内存),并且对 Postgres 查询计划器可见。

HypoPG 的动机是允许用户快速搜索索引以改进缓慢查询,而无需消耗服务器资源或等待索引构建完成。

启用扩展#

  1. 转到仪表板中的 数据库 页面。
  2. 在侧边栏中单击 扩展
  3. 搜索 hypopg 并启用该扩展。

加速查询#

给定以下表和一个简单的查询,用于按 id 从表中选择

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

我们可以生成一个 explain plan,以描述 Postgres 查询计划器打算如何执行该查询。

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

使用 HypoPG,我们可以在 account(id) 列上创建一个假设索引,以检查它对查询计划器是否有用,然后重新运行 explain plan。

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

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

查询计划已从 Seq Scan 更改为使用新创建的虚拟索引的 Index Scan,因此我们可以选择创建实际版本的索引以提高目标查询的性能

1
create index on account(id);

函数#

资源#