A B-tree cannot index the inside of a JSONB document or a bag of words in a text column. Point either kind of query at a large table without the right index and Postgres falls back to a sequential scan — reading every row on every request. GIN is the index type built for exactly this: values with many keys inside them.
GIN stands for Generalised Inverted Index. Where a B-tree maps one row to one key, an inverted index maps each contained element — each JSONB key and value, each lexeme in a document — back to the rows that hold it. That is what lets a containment query or a text search jump straight to the matching rows instead of scanning the table. This is a build-and-verify walkthrough on PostgreSQL 17: a GIN index on a JSONB column, then a full-text index over a generated tsvector, with the write-side and usage-checking details that decide whether the index actually earns its keep. If you want the wider map of index types first, we have a Postgres index type cheat-sheet that places GIN alongside B-tree, BRIN and hash.
Indexing a JSONB column for containment
Take a table of events with a JSONB payload. Without an index, a containment query using the @> operator has to deserialise and inspect the JSONB in every row.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ts timestamptz NOT NULL DEFAULT now(),
doc jsonb NOT NULL
);
-- Find rows whose doc contains this key/value pair.
-- With no GIN index this is a sequential scan.
SELECT id, ts
FROM events
WHERE doc @> '{"type": "login", "ok": false}';
The default GIN operator class for JSONB is jsonb_ops. It indexes every key and every value in the document, which makes it the broad choice: it supports the key-exists operators ?, ?| and ?&, the containment operator @>, and the jsonpath match operators @? and @@.
-- Default operator class: indexes keys AND values.
CREATE INDEX events_doc_gin ON events USING gin (doc);
If your queries only ever use containment and jsonpath — never the key-exists operators — the non-default jsonb_path_ops class is usually the better tool. It stores a hash of each path-plus-value rather than indexing bare keys, so the index is smaller and containment lookups are faster. The trade is narrower coverage: it supports @>, @? and @@ only, and cannot answer ?, ?| or ?&.
-- Smaller, faster for @> containment; no key-exists support.
CREATE INDEX events_doc_gin_path ON events USING gin (doc jsonb_path_ops);
Pick one, not both, per column unless you have measured a reason. My default is jsonb_path_ops when the access pattern is containment-only, and the plain jsonb_ops when a service also asks “does this key exist”. Confirm the planner actually uses it with EXPLAIN (ANALYZE, BUFFERS) — you want a Bitmap Index Scan on the GIN index, not a Seq Scan. If it stays on a sequential scan, the table may simply be too small for the planner to bother, or the operator in your query may not be one the operator class supports. Our note on why Postgres ignores an index covers the usual culprits.
A full-text index over a generated tsvector
Full-text search works on the tsvector type — a document reduced to normalised lexemes. You can compute it inline in every query, but the disciplined approach on Postgres 12 and later is a generated column, so the tsvector is stored, stays in step with the source text, and can be indexed directly.
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
-- Stored, always in sync with title + body.
search tsvector GENERATED ALWAYS AS (
to_tsvector('english',
coalesce(title, '') || ' ' || coalesce(body, ''))
) STORED
);
CREATE INDEX articles_search_gin ON articles USING gin (search);
Queries then match the stored vector against a tsquery. Use to_tsquery for operator syntax you control, or plainto_tsquery/websearch_to_tsquery for raw user input.
-- Uses the GIN index on the generated column.
SELECT id, title,
ts_rank(search, query) AS rank
FROM articles,
to_tsquery('english', 'postgres & (index | scan)') AS query
WHERE search @@ query
ORDER BY rank DESC
LIMIT 20;
One trap worth naming: the text search configuration you build the column with ('english' here) must match the one you query with, or stemming will not line up and results will quietly go wrong. Fix the configuration in both places.
Why GIN builds are slow, and the write-side cost
GIN indexes are expensive to build because each row expands into many index entries — one per key, value or lexeme — and all of them must be sorted and merged into the posting lists. On a large table, budget for it: raise maintenance_work_mem before a big CREATE INDEX, and reach for CREATE INDEX CONCURRENTLY in production so you do not take a write lock on the table for the duration.
Inserts and updates carry a cost too, and this is where GIN has a specific mechanism. By default the fastupdate storage parameter is on: new entries land in an unsorted pending list rather than being merged into the main structure immediately, which keeps write latency low. The catch is that every search must scan the pending list on top of the main index, so a large pending list drags query time down. The list is flushed into the main index by autovacuum, or when it grows past gin_pending_list_limit (default 4MB). Two levers follow from that.
- If you need consistent read latency more than fast writes — a search-heavy table — turn
fastupdateoff so entries go straight into the index:ALTER INDEX articles_search_gin SET (fastupdate = off); - If you keep fastupdate on, tune
gin_pending_list_limit(per-index via the storage parameter, or globally) so the list is flushed before it grows large enough to hurt searches.
Verify the index is actually being used
An index that no query touches is pure write-amplification and wasted disk. Before you consider the job done, check that the planner reaches for it under real traffic. pg_stat_user_indexes exposes the scan count.
SELECT indexrelname,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname IN ('events', 'articles')
ORDER BY idx_scan;
An idx_scan of zero after a representative period means the index is not serving queries — either the workload does not use the operators it supports, or the planner is choosing a scan because the table is small or the statistics are stale. GIN gives you containment and full-text search that a B-tree cannot, but only for the operators it indexes; it does no good on a range query or an ordinary equality lookup, and it will not deliver an index-only scan the way a covering B-tree with INCLUDE can. Build it for the query you actually run, then confirm the plan changed. An index nobody’s queries hit is just a slower way to write rows.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Can you trust the architecture you have?
Architecture diagrams rarely show the reality of how systems actually operate. An independent review establishes what is really there.