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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which relations are involved here?
- `carts`, `pg_indexes` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.