HypoPG: 假设性索引
HypoPG
是 PostgreSQL 的一个扩展,用于创建假设/虚拟索引。HypoPG 允许用户快速创建对 Postgres 查询规划器可见的假设/虚拟索引,这些索引不会消耗任何服务器资源(CPU、磁盘、内存)。
HypoPG 的设计初衷是让用户能够在不消耗服务器资源或等待索引构建的情况下,快速寻找能改善慢查询的索引方案。
启用扩展
- 进入 Dashboard 的数据库页面
- 在侧边栏点击 Extensions
- 搜索
hypopg
并启用该扩展
加速查询性能
给定以下表格和一个通过id
从表中查询数据的简单SQL语句:
1234567891011create 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查询规划器打算如何执行该查询。
1234567explain 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
语句应该在同一个查询中执行。
123456789select * 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
(索引扫描),因此我们可以选择创建真实的索引来提升目标查询的性能:
1create index on account(id);
函数
hypo_create_index(text)
: 用于创建假设索引的函数。hypopg_list_indexes
: 列出所有已创建假设索引的视图。hypopg()
: 以与pg_index
相同的格式列出所有已创建假设索引的函数。hypopg_get_index_def(oid)
: 显示创建该索引所需的create index
语句的函数。hypopg_get_relation_size(oid)
: 估算假设索引大小的函数。hypopg_drop_index(oid)
: 通过oid
删除指定假设索引的函数。hypopg_reset()
: 删除所有假设索引的函数。
相关资源
- 官方 HypoPG 文档