jsonb_path_ops GIN Index Matches Containment

Create a GIN index with jsonb_path_ops, query containment with @>, and compare it with jsonb_ops for key-existence filters.

SqlData Fetching

Code

snippet
-- jsonb_path_ops:只为“路径 + 值”建索引,体积小于默认 jsonb_ops
-- It accelerates containment (@>) but not key-existence operators
CREATE INDEX IF NOT EXISTS carts_payload_path_ops
  ON carts USING gin (payload jsonb_path_ops);

-- 支持 @> 包含查询,包括数组元素匹配
SELECT id, payload
FROM carts
WHERE payload @> '{"items": [{"sku": "A-1"}]}'
ORDER BY id;

-- 与默认操作符类对比索引体积
SELECT pg_size_pretty(pg_relation_size('carts_payload_path_ops')) AS path_ops_size;

-- jsonb_path_ops 不支持键存在运算符 ?、?|、?&,这类查询需要 jsonb_ops
CREATE INDEX IF NOT EXISTS carts_payload_ops
  ON carts USING gin (payload jsonb_ops);

SELECT id
FROM carts
WHERE payload ? 'coupon';

-- 查看索引定义,确认操作符类
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'carts'
ORDER BY indexname;

How it works

Several statements share this file — SELECT / CREATE, with carts and pg_indexes among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

Using it

The carts table is the working surface here.

Key statements

SELECT id, payload
FROM carts
WHERE payload @> '{"items": [{"sku": "A-1"}]}'
ORDER BY id;
SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'carts'
ORDER BY indexname;
SELECT id
FROM carts
WHERE payload ? 'coupon';

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`carts`, `pg_indexes` — referenced directly, no join needed.