Sub topic 12
Indexing with GIN
This chapter assumes you can already build a weighted tsvector in a generated column and match it with @@, as the earlier chapters show. Here you add a GIN index so those matches stop scanning every row. You will also see what the index stores, how to confirm the planner uses it, and what it costs on writes.
What GIN stores
GIN stands for Generalized Inverted Index. A B-tree maps a whole column value to a row. GIN maps each element inside a value to the rows that contain it. For a tsvector, the elements are lexemes.
Suppose three rows contain these lexemes:
| Row | Lexemes in the tsvector |
|---|---|
| 1 | `fox`, `jump`, `quick` |
| 2 | `dog`, `fox`, `lazi` |
| 3 | `dog`, `search` |
The index holds one entry per distinct lexeme, each with a sorted list of row pointers (a posting list):
dog: rows 2, 3fox: rows 1, 2jump: row 1lazi: row 2quick: row 1search: row 3
To answer fox & dog, PostgreSQL looks up each lexeme and intersects the lists. The result is row 2. It never reads the other rows. Large posting lists are stored in compressed trees, so common lexemes stay cheap to keep.
Creating the index
The usual pattern is a GIN index on the stored generated column from the previous chapter:
CREATE TABLE articles (
id bigserial PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED
);
CREATE INDEX articles_search_idx ON articles USING gin (search);GIN is the default choice for full-text search because it answers lookups quickly and works well when many rows share lexemes. The trade-off is slower writes and a larger index than GiST would give you. The GiST chapter covers that alternative.
Checking that the index is used
Load a few rows and run EXPLAIN:
INSERT INTO articles (title, body) VALUES
('Full text search', 'PostgreSQL turns documents into lexemes and matches them with a query.'),
('Indexing basics', 'A GIN index maps each lexeme to the rows that contain it.'),
('Backups', 'Use pg_dump to export a database.');
ANALYZE articles;
SET enable_seqscan = off;
EXPLAIN
SELECT id, title
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'lexeme index');You should see a plan of this shape:
Bitmap Heap Scan on articles
Recheck Cond: (search @@ '''lexem'' & ''index'''::tsquery)
-> Bitmap Index Scan on articles_search_idx
Index Cond: (search @@ '''lexem'' & ''index'''::tsquery)SET enable_seqscan = off is only for this experiment. On a table of three rows the planner correctly prefers a sequential scan, because reading one page is cheaper than visiting an index. Turn the setting back on with RESET enable_seqscan; afterwards. Never leave it off in application code.
The plan is a bitmap scan. The index builds a bitmap of candidate pages, then the heap is read and the Recheck Cond is applied. GIN can return false positives in some cases, such as phrase queries or weight-restricted matches, so the recheck is normal.
The query must match the indexed expression
If you index a column, queries that use the column can use the index. If you index an expression instead, the query must contain exactly the same expression:
CREATE INDEX articles_expr_idx
ON articles USING gin (to_tsvector('english', title || ' ' || body));
-- Can use the index: same expression, same configuration
SELECT id FROM articles
WHERE to_tsvector('english', title || ' ' || body) @@ to_tsquery('english', 'lexeme');
-- Cannot use it: different configuration
SELECT id FROM articles
WHERE to_tsvector('simple', title || ' ' || body) @@ to_tsquery('simple', 'lexeme');Expression indexes must use the two-argument to_tsvector with an explicit configuration. The one-argument form depends on the default_text_search_config setting, which can change, so PostgreSQL does not allow it in an index expression. A stored generated column avoids both problems. The expression lives in one place and the query only names the column.
What the index does not speed up
- Ranking.
ts_rankcomputes a score from each matching row'stsvector. The index finds the matches, then PostgreSQL reads each one to rank it. A query that matches 500,000 rows still ranks 500,000 rows beforeLIMIT 10applies, so broad queries on large tables stay slow. - Purely negative queries.
!mysqlalone matches almost every row, so the planner usually chooses a sequential scan. Pair negations with at least one positive term. - Very common lexemes. A query on a lexeme present in most rows returns most of the table. The planner may skip the index. That is correct behavior, not a bug.
- Substring searches.
LIKE '%ing%'is not a full-text operation. GIN on atsvectordoes not help it. A trigram index does, which a later chapter covers.
Write cost and the pending list
One inserted document with 200 distinct lexemes touches up to 200 posting lists. To avoid doing all that work inside each INSERT, GIN has a fast-update mechanism. New entries go into an unsorted pending list. They are merged into the main structure in bulk when the list exceeds gin_pending_list_limit (4MB by default), during VACUUM, or when gin_clean_pending_list() is called.
This has two consequences:
- Inserts stay fast on average, but the insert that triggers the merge pays for it. You may see occasional latency spikes.
- Searches must also scan the pending list. A large list slows reads until it is flushed.
You can tune this per index:
-- Flush more often, keeping reads steadier
ALTER INDEX articles_search_idx SET (gin_pending_list_limit = 512);
-- Or disable the pending list: slower writes, predictable reads
ALTER INDEX articles_search_idx SET (fastupdate = off);The limit is in kilobytes. Choose by workload. A write-heavy ingest pipeline benefits from the default. A read-latency-sensitive API on slowly changing data may prefer fastupdate = off.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Sequential scan on a large table | Query expression differs from the index expression, or configuration differs | Query the stored column, or copy the exact expression |
| `functions in index expression must be marked IMMUTABLE` | One-argument `to_tsvector` used in `CREATE INDEX` | Pass the configuration name explicitly |
| Index ignored on a small table | Planner estimates a scan is cheaper | Test with `enable_seqscan = off`, or use realistic data volumes |
| Slow query despite index | Query matches most rows, or ranking is applied to a huge match set | Add more selective terms, filter first, or reduce the matched set |
| Occasional slow `INSERT` | Pending list flush | Lower `gin_pending_list_limit` or set `fastupdate = off` |
| Stale planner choices | Missing statistics | Run `ANALYZE` after bulk loads |
Exercise
You created CREATE INDEX docs_idx ON docs USING gin (to_tsvector('english', body));. A teammate's query uses WHERE to_tsvector(body) @@ to_tsquery('fox') and runs a sequential scan on a large table. Explain why, and give the fix.
Show answer
The query uses the one-argument to_tsvector, which relies on the session's default configuration. That is a different expression from the indexed to_tsvector('english', body), so the planner cannot use the index. Rewrite the query as WHERE to_tsvector('english', body) @@ to_tsquery('english', 'fox'). Better still, store the vector in a generated column, index that column, and query it directly.
Exercise
A table has a GIN index on a tsvector column. Searches are fast, but a few INSERT statements out of thousands take far longer than the rest. What causes this, and name two ways to reduce it.
Show answer
GIN buffers new entries in a pending list and merges them into the main index when the list passes gin_pending_list_limit. The insert that triggers the merge pays the whole cost. You can lower gin_pending_list_limit so flushes are smaller and more frequent, or set fastupdate = off so every insert updates the index directly. Running VACUUM regularly also flushes the list outside request paths.