[ PROMPT_NODE_25128 ]
query-index-types
[ SKILL_DOCUMENTATION ]
## 为数据选择正确的索引类型
不同的索引类型擅长处理不同的查询模式。默认的 B-tree 并不总是最优的。
**错误做法(对 JSONB 包含查询使用 B-tree):**
sql
-- B-tree 无法优化包含运算符
create index products_attrs_idx on products (attributes);
select * from products where attributes @> '{"color": "red"}';
-- 全表扫描 - B-tree 不支持 @> 运算符
**正确做法(对 JSONB 使用 GIN):**
sql
-- GIN 支持 @>, ?, ?&, ?| 运算符
create index products_attrs_idx on products using gin (attributes);
select * from products where attributes @> '{"color": "red"}';
索引类型指南:
sql
-- B-tree (默认): =, , BETWEEN, IN, IS NULL
create index users_created_idx on users (created_at);
-- GIN: 数组, JSONB, 全文搜索
create index posts_tags_idx on posts using gin (tags);
-- BRIN: 大型时间序列表 (体积小 10-100 倍)
create index events_time_idx on events using brin (created_at);
-- Hash: 仅等值比较 (对于 = 略快于 B-tree)
create index sessions_token_idx on sessions using hash (token);
参考:[索引类型 (Index Types)](https://www.postgresql.org/docs/current/indexes-types.html)