[ PROMPT_NODE_23504 ]
advanced-jsonb-indexing
[ SKILL_DOCUMENTATION ]
## 为 JSONB 列建立索引以实现高效查询
未建立索引的 JSONB 查询会扫描整个表。请使用 GIN 索引进行包含查询。
**错误做法(未对 JSONB 建立索引):**
sql
create table products (
id bigint primary key,
attributes jsonb
);
-- 每次查询都会进行全表扫描
select * from products where attributes @> '{"color": "red"}';
select * from products where attributes->>'brand' = 'Nike';
**正确做法(为 JSONB 使用 GIN 索引):**
sql
-- 用于包含运算符 (@>, ?, ?&, ?|) 的 GIN 索引
create index products_attrs_gin on products using gin (attributes);
-- 现在包含查询将使用索引
select * from products where attributes @> '{"color": "red"}';
-- 对于特定键的查找,请使用表达式索引
create index products_brand_idx on products ((attributes->>'brand'));
select * from products where attributes->>'brand' = 'Nike';
选择正确的运算符类:
sql
-- jsonb_ops (默认): 支持所有运算符,索引较大
create index idx1 on products using gin (attributes);
-- jsonb_path_ops: 仅支持 @> 运算符,但索引体积小 2-3 倍
create index idx2 on products using gin (attributes jsonb_path_ops);
参考:[JSONB 索引](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING)