Part 14 / Topic 7 of 10
Indexing JSONB
Structural queries over big jsonb tables want an index, and the one built for "contains" questions is GIN (Generalized Inverted Index — think: index every key and value, like a book's index):
CREATE INDEX events_payload_gin ON events USING gin (payload);
CREATE INDEX
A GIN index on a jsonb column accelerates exactly the structural operators — @>, ?, ?|, ?& and jsonpath (@@) — which is why section 3 steered you toward @> filters. It does not help payload ->> 'device' = 'mobile': that's a text extraction compared with =, invisible to the jsonb index (an expression index on the extraction would — Stage 4's lesson). shopdb's seven events don't need any of this; the shape of the decision does: write containment queries, back them with GIN, at the point measurements say so.
🧪 Quick quiz — answer from memory, then check.
- Which operators does a GIN jsonb index serve?
- Why doesn't it help
payload ->> 'k' = 'v'?
Show the answers
- The structural ones:
@>,?,?|,?&, and jsonpath matches. - That's an extracted-text equality, not a containment — it needs its own expression index.
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.