JSONB Scalar Equality Expression Index
GIN indexes serve containment on jsonb, but scalar equality on payload->>'key' needs a btree expression index built on that exact expression.
Code
-- GIN serves @> containment on jsonb; scalar equality needs an expression index
CREATE TEMP TABLE webhook_events (
id bigint PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO webhook_events VALUES
(1, '{"event": "push", "repo": "api"}'),
(2, '{"event": "merge", "repo": "web"}'),
(3, '{"event": "push", "repo": "web"}');
-- GIN:@> 包含查询的通道
CREATE INDEX webhook_payload_gin ON webhook_events USING gin (payload);
SELECT id FROM webhook_events WHERE payload @> '{"event": "push"}';
-- payload->>'event' 是逐行解包出的 scalar text:普通 GIN 不服务等值比较
-- 要在同一个表达式上建 expression index(双括号是表达式索引语法)
CREATE INDEX webhook_event_text_idx
ON webhook_events ((payload->>'event'));
EXPLAIN (COSTS OFF)
SELECT id
FROM webhook_events
WHERE payload->>'event' = 'push';Two access paths for two query shapes
The GIN index on payload serves containment: WHERE payload @> '{"event": "push"}' goes through webhook_payload_gin, because GIN indexes jsonb’s topological keys-and-values structure. Scalar equality is a different shape — payload->>'event' = 'push' unwraps the value to text per row — and a plain GIN does not serve that comparison. The fix is a btree expression index built on the exact same expression, ((payload->>'event')), where the doubled parentheses are the expression-index syntax the comment mentions.
What each query returns
id
----
1
3
Both queries match the same two rows (the ‘push’ events; the ‘merge’ row 2 is excluded). The difference is only the plan: the EXPLAIN (COSTS OFF) for the equality form shows a scan driven by webhook_event_text_idx (exact node naming varies by version), which is what the expression index was created to provide — without it, that shape degrades to a sequential scan.
The line that pins the expression
CREATE INDEX webhook_event_text_idx
ON webhook_events ((payload->>'event'));
The index expression must match the query text exactly (payload->>'event', not an equivalent rewrite) for the planner to recognize the match — that exactness is the price of scalar equality on jsonb.
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `webhook_events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.