PostgreSQL JSONB GIN Index Containment
Query JSONB documents with containment operators backed by a GIN index, comparing jsonb_path_query for complex predicates.
Code
-- PostgreSQL GIN 索引让 @> 包含查询走索引
CREATE INDEX idx_events_payload
ON events USING gin (payload jsonb_path_ops);
-- 包含运算符:文档包含给定结构即命中
SELECT
event_id,
payload->>'kind' AS kind,
payload->'context'->>'region' AS region
FROM events
WHERE payload @> '{"context": {"region": "eu"}}'
ORDER BY created_at DESC
LIMIT 20;
-- 顶层数组包含:tags 数组含指定值
SELECT event_id, payload->'tags' AS tags
FROM events
WHERE payload->'tags' @> '["checkout"]'
AND payload ? 'priority'; -- 顶层键存在性
-- jsonpath:复杂条件的结构化表达
SELECT
event_id,
jsonb_path_query_first(
payload,
'$.metrics[*] ? (@.name == "latency_ms" && @.value > 500).value'
) AS slow_latency
FROM events
WHERE jsonb_path_exists(
payload,
'$.metrics[*] ? (@.name == "latency_ms" && @.value > 500)'
);What the code does
The file runs SELECT / CREATE statements, touching events.
In terms of clauses, the statements use: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Applying it
Run the statement against the events table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT
event_id,
jsonb_path_query_first(
payload,
'$.metrics[*] ? (@.name == "latency_ms" && @.value > 500).value'
) AS slow_latency
FROM events
WHERE jsonb_path_exists(
payload,
'$.metrics[*] ? (@.name == "latency_ms" && @.value > 500)'
);
SELECT
event_id,
payload->>'kind' AS kind,
payload->'context'->>'region' AS region
FROM events
WHERE payload @> '{"context": {"region": "eu"}}'
ORDER BY created_at DESC
LIMIT 20;
SELECT event_id, payload->'tags' AS tags
FROM events
WHERE payload->'tags' @> '["checkout"]'
AND payload ? 'priority'; -- 顶层键存在性
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
- What objects does the SQL involve?
- `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.