Sub topic 7
GIN: indexing jsonb, arrays, and full-text search
This chapter assumes you can read a basic EXPLAIN plan and know how a B-tree index works. It also assumes you are comfortable with jsonb, array, and tsvector columns. A B-tree maps one value to one row. That model breaks when a single column value holds many searchable parts, such as the keys in a JSON document, the elements of an array, or the words in a text. GIN (Generalized Inverted Index) is built for that case.
How GIN stores data
A GIN index is an inverted index. It does not store one entry per row. It extracts keys from each indexed value, then stores each distinct key once with a posting list: the list of row locations (heap tuple IDs) that contain that key.
For a text[] column, the keys are the array elements. For a tsvector, they are the lexemes (normalized words). For jsonb, they are keys and values, depending on the operator class.
To answer "rows containing both postgres and index", GIN fetches two posting lists and intersects them. Only rows 4 and 9 survive. This is why GIN is fast for "contains" queries over composite values, and why a B-tree on the whole column cannot do the same job.
Three consequences follow from this design:
- A GIN index supports only the operators its operator class defines. It does not support
<,>, orORDER BY. - GIN scans are bitmap scans. The planner reads the index, builds a bitmap of matching pages, and then visits the heap. GIN does not offer plain index scans, and it does not offer index-only scans.
- One inserted row can produce many key entries, so writes are more expensive than with a B-tree.
Indexing jsonb
Create a table and load enough rows for the planner to care:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO events (payload)
SELECT jsonb_build_object(
'type', CASE WHEN i % 100 = 0 THEN 'login' ELSE 'view' END,
'user_id', i,
'tags', jsonb_build_array('web', 'beta')
)
FROM generate_series(1, 200000) AS i;
CREATE INDEX events_payload_gin_idx
ON events USING gin (payload);
ANALYZE events;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM events
WHERE payload @> '{"type": "login"}';The plan should show a Bitmap Heap Scan on top of a Bitmap Index Scan on events_payload_gin_idx. The heap node has a Recheck Cond line. GIN can return candidates that need to be rechecked against the actual row. The Rows Removed by Index Recheck counter shows how many were discarded.
Choosing between jsonb_ops and jsonb_path_ops
jsonb has two operator classes for GIN.
| Operator class | Default | Operators supported | Size and speed | Column |
|---|---|---|---|---|
| `jsonb_ops` | yes | `@>`, `?`, `?\ | `, `?&`, `@?`, `@@` | Larger. Every key and every value is indexed as a separate entry. |
| `jsonb_path_ops` | no | `@>`, `@?`, `@@` | Smaller and usually faster for `@>`. It indexes a hash of each path to a value. |
If you only run containment queries, jsonb_path_ops is usually the better choice:
CREATE INDEX events_payload_path_idx
ON events USING gin (payload jsonb_path_ops);
-- Served by either operator class
SELECT id FROM events WHERE payload @> '{"type": "login"}';
-- Served only by jsonb_ops: key existence
SELECT id FROM events WHERE payload ? 'user_id';Use the default jsonb_ops when you need the ? family of operators. Otherwise try jsonb_path_ops and compare index sizes.
What a GIN index on a jsonb column cannot do
A GIN index on payload does not help a query that extracts a value first:
-- Does NOT use the GIN index on payload
SELECT id FROM events WHERE payload ->> 'type' = 'login';The expression payload ->> 'type' is not an indexed operator. You have two options. Rewrite the query to use containment (payload @> '{"type": "login"}'), or create a B-tree expression index on the extracted value:
CREATE INDEX events_type_idx ON events ((payload ->> 'type'));The second option is smaller and better when you filter on one known key with = or a range. The GIN index is better when queries vary over many keys.
Containment is also strict about structure. payload @> '{"tags": ["web"]}' matches because the array in the document contains "web". A containment query matches at the level you write it, so '{"web": 1}' would not match a document that has web only inside an array.
Indexing arrays
For array columns, the default operator class array_ops supports @> (contains), <@ (is contained by), && (overlaps), and =:
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
CREATE INDEX articles_tags_gin_idx
ON articles USING gin (tags);
-- Has all of these tags
SELECT id FROM articles WHERE tags @> ARRAY['postgres', 'index'];
-- Has at least one of these tags
SELECT id FROM articles WHERE tags && ARRAY['gin', 'gist'];The query 'gin' = ANY (tags) does not use the index. Write it as tags @> ARRAY['gin'] instead. Also make sure the types match. The literal ARRAY['gin'] is text[], which fits a text[] column. A mismatch such as comparing an integer[] column to bigint[] can prevent index use.
Indexing full-text search
Full-text search turns a document into a tsvector (a sorted list of lexemes with positions) and a search into a tsquery. The @@ operator tests for a match. GIN indexes the lexemes of the tsvector.
The simplest approach is an expression index:
CREATE TABLE docs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL
);
CREATE INDEX docs_fts_idx
ON docs USING gin (to_tsvector('english', body));
SELECT id FROM docs
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'index & postgres');Two rules apply here:
- You must pass the text search configuration (
'english') explicitly. The one-argument form ofto_tsvectordepends on the session settingdefault_text_search_config, so it is not immutable and cannot be used in an index expression. - The query must use the same expression, with the same configuration. If the query calls
to_tsvector('simple', body), the planner will not use an index built with'english'.
Storing the tsvector in a generated column
An expression index recomputes to_tsvector for each row during the recheck step, which costs CPU. A stored generated column avoids repeating the expression in every query and keeps the configuration in one place:
CREATE TABLE articles_fts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL,
body_tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED
);
CREATE INDEX articles_fts_tsv_idx
ON articles_fts USING gin (body_tsv);
SELECT id FROM articles_fts
WHERE body_tsv @@ websearch_to_tsquery('english', 'postgres index');The trade-off is extra disk space for the stored column. The gain is simpler queries and no repeated parsing. Note that the index is only on lexemes, not on ranking. Functions such as ts_rank still run on the matching rows after the index narrows them down.
Write cost and the pending list
Because one row can generate many keys, a plain GIN insert would have to update many posting lists. To cut that cost, GIN uses fast update by default. New entries go into a small unsorted pending list, and the pending list is merged into the main structure in bulk. The merge happens when the list exceeds gin_pending_list_limit (4 MB by default), during VACUUM, or on gin_clean_pending_list().
This has a visible effect. Inserts are faster on average, but a query has to scan the pending list as well as the main index. Occasionally, one unlucky insert pays for the whole merge, which shows up as a latency spike. You can tune this per index:
-- Predictable insert latency, slower average writes
ALTER INDEX events_payload_gin_idx SET (fastupdate = off);
-- Or keep fast update but make the pending list smaller (value in kB)
ALTER INDEX events_payload_gin_idx SET (gin_pending_list_limit = 1024);Setting fastupdate = off is worth considering when latency consistency matters more than throughput. For read-heavy tables, the defaults are normally fine.
When the planner skips a GIN index
An unused GIN index is usually one of these cases:
- The operator is not in the operator class. For example,
->>equality,= ANY, orLIKEon a plain text column. Check the operator list for your class. - The expression differs. A full-text query with a different configuration, or a different expression than the one indexed.
- The match is not selective. If a key such as
"web"appears in most rows, the bitmap covers nearly every page and a sequential scan is cheaper. - Statistics are stale or the table is tiny. Run
ANALYZE. For experiments on small tables,SET enable_seqscan = off;in a session shows whether the planner could use the index. Do not leave that setting on in production.
When a query combines a rare key with a common one, GIN handles that well. It intersects the posting lists, and the rare key keeps the result small.
Comparing GIN to the alternatives
- GIN versus a B-tree expression index. Use B-tree when you query one known extracted value with
=or a range. Use GIN when queries search across many keys or elements. - GIN versus GiST for text search. Both can index a
tsvector. GIN is usually faster for lookups and bigger and slower to update. GiST is lossy for text search and usually slower to query, but cheaper to write. Pick GIN for read-heavy search. - GIN versus trigram search. For substring and
ILIKEsearches, use GIN with thegin_trgm_opsoperator class frompg_trgm. That is a case of choosing a non-default operator class, covered in its own chapter.
Exercise
A table has a column meta jsonb. Your application runs WHERE meta @> '{"plan": "pro"}' on a large table, and you never use the ? operators. Which GIN operator class should you try first, and what query would you write to find rows that have the "plan" key regardless of its value?
Show answer
Try jsonb_path_ops, because it is smaller and usually faster for @> queries. It does not support the ? key-existence operator, so a query such as WHERE meta ? 'plan' would need the default jsonb_ops class instead. That means a second index, or switching to jsonb_ops if key-existence queries are common.
Exercise
You created CREATE INDEX docs_fts_idx ON docs USING gin (to_tsvector('english', body));. A teammate runs WHERE to_tsvector(body) @@ to_tsquery('postgres') and gets a sequential scan. Why, and how do you fix the query?
Show answer
The query uses the one-argument to_tsvector, which is a different expression from the indexed to_tsvector('english', body). The planner can only use an expression index when the query contains the same expression. Fix it by writing WHERE to_tsvector('english', body) @@ to_tsquery('english', 'postgres').
Exercise
Inserts into a table with a GIN index are fast on average, but a few inserts take much longer. What causes this, and which index setting changes the behavior?
Show answer
GIN fast update collects new entries in a pending list and merges them into the main index in bulk when the list passes gin_pending_list_limit. The insert that triggers the merge pays for it, which causes a latency spike. Setting fastupdate = off on the index makes each insert update the index directly, so latency is steadier but average write throughput drops.