liveBook · Manning

GIN index

As explained in Just Use Postgres!

GIN is a PostgreSQL index access method designed for indexing composite values such as arrays and full-text search vectors.

A GIN (generalized inverted index) is a PostgreSQL index access method for composite values, especially JSON data, arrays, and full-text-search lexemes. Unlike the default B-tree, it stores searchable components separately and maps each component to table rows. Create one with the USING GIN clause. section 4.2 section 6.6.1

Use GIN when queries search inside a value rather than compare one scalar value:

  • Index a JSONB column with CREATE INDEX idx_pizza_orders_gin ON pizzeria.order_items USING GIN(pizza); The default operator class extracts JSON keys, values, and array elements as index entries. section 5.6.2
  • Search JSONB with containment or key-existence operators, such as pizza @> '{"type": "custom"}' or pizza ? 'special_instructions'. PostgreSQL can use the GIN index through a Bitmap Index Scan. section 5.6.2
  • Index a tsvector column for full-text search: CREATE INDEX idx_movie_lexemes_gin ON omdb.movies USING GIN (lexemes); Each unique lexeme references rows containing it. section 6.6.1

JSON containment and full-text search

A pizza query using pizza @> '{"sauce": "pesto"}' and pizza @> '{"size": "small"}' returns 35 rows through a Bitmap Index Scan and Bitmap Heap Scan. A movie query using lexemes @@ to_tsquery('historical & fight') returns three rows; after adding the GIN index, execution changes from a sequential scan taking 15.328 ms to a bitmap plan taking 0.150 ms. Nested JSON containment can require heap rechecks, as shown by 90 rows removed during recheck.

CREATE INDEX new_index_name ON tableA(columnA);

Compare the default CREATE INDEX form with the USING GIN form to see where the access method is selected. section 4.2

How Just Use Postgres! covers it

How deep it goes
Explains extracted index entries, row references, operator classes, bitmap plans, and heap rechecks, but omits implementation-level maintenance internals.
Examples
Demonstrates pizza-order JSONB searches, jsonb_path_ops size comparisons, and movie searches over normalized historical and fight lexemes.
What it assumes
Assumes familiarity with CREATE INDEX, JSONB operators, tsvector columns, and EXPLAIN; demonstrates the indexing choices from concrete queries.
What you can do after
Apply it via PostgreSQL SQL by creating GIN indexes and verifying Bitmap Index Scan plans with EXPLAIN.
How it connects
Connects JSONB, full-text search, tsvector, GiST, RUM, B-tree, and jsonb_path_ops.

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 Just Use Postgres!. The section links point to the parts of the book it draws on.