liveBook · Manning

GIN index

As explained in PostgreSQL Mistakes and How to Avoid Them

GIN is a PostgreSQL index access method designed for efficiently indexing composite values such as arrays and JSONB documents.

A GIN (Generalized Inverted Index) is PostgreSQL’s practical choice for searching composite values such as JSONB documents and tsvector text. A common mistake is applying a B-tree expression index to document text: it can support equality or prefix matching, but not arbitrary substrings, and long values can exceed B-tree entry limits. section 4.4

Choose the index according to the predicate:

  • Use GIN with to_tsvector for token-oriented full-text queries using @@ and plainto_tsquery. section 4.4
  • Use GIN directly on JSONB for containment predicates such as data @> '{"doi": ...}'. section 4.4
  • Prefer a focused B-tree expression index for equality on one extracted JSONB field, such as data->>'doi'. section 4.4

Indexing article titles

CREATE INDEX ON test.arxiv USING gin (to_tsvector('english', data->>'title')); SELECT data->'doi' FROM test.arxiv WHERE to_tsvector('english', data->>'title') @@ plainto_tsquery('english', 'modeling of hydrogen'); EXPLAIN ANALYZE reports a Bitmap Index Scan and roughly 5 ms execution, replacing the multisecond sequential scan caused by '%modeling of hydrogen%'. section 4.4

DROP INDEX test.arxiv_lower_idx;
DROP INDEX

CREATE INDEX ON test.arxiv
    USING gin (to_tsvector('english', data->>'title'));
CREATE INDEX

Inspect the executable GIN definition for a JSONB-derived title search. section 4.4

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Explains index selection through SQL definitions, EXPLAIN plans, timings, and size comparisons, without covering GIN internals.
Examples
Uses an arXiv JSONB dataset, article-title searches, abstract-size failure, DOI containment, and DOI equality queries.
What it assumes
Assumes SQL, JSONB operators, indexes, and EXPLAIN familiarity while reinforcing practical index selection.
What you can do after
Apply it via PostgreSQL SQL by matching GIN definitions to full-text or JSONB containment predicates.
How it connects
Connects GIN with B-tree indexes, JSONB, tsvector, full-text search, expression indexes, and bitmap heap scans.

Also explained in

Compare how 2 books explain GIN index →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.