HypoPG:假设索引
HypoPG 是 Postgres 扩展,用于创建假设/虚拟索引。HypoPG 允许用户快速创建假设/虚拟索引,这些索引不会产生资源消耗(CPU、磁盘、内存),并且对 Postgres 查询计划器可见。
HypoPG 的动机是允许用户快速搜索索引以改进缓慢查询,而无需消耗服务器资源或等待索引构建完成。
启用扩展#
- 转到仪表板中的 数据库 页面。
- 在侧边栏中单击 扩展。
- 搜索
hypopg并启用该扩展。
加速查询#
给定以下表和一个简单的查询,用于按 id 从表中选择
1create table account (2 id int,3 address text4);56insert into account(id, address)7select8 id,9 id || ' main street'10from11 generate_series(1, 10000) id;我们可以生成一个 explain plan,以描述 Postgres 查询计划器打算如何执行该查询。
1explain select * from account where id=1;23 QUERY PLAN4-------------------------------------------------------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 语句应在单个查询中执行。
1select * from hypopg_create_index('create index on account(id)');23explain select * from account where id=1;45 QUERY PLAN6------------------------------------------------------------------------------------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,因此我们可以选择创建实际版本的索引以提高目标查询的性能
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 文档