Sub topic 13
GiST as an alternative index
This chapter assumes you have the weighted search column and the GIN index on articles from the previous chapters. You should also be comfortable reading EXPLAIN output. GIN is the usual choice for full-text search. GiST is the other index type that can serve @@ queries, and it behaves quite differently.
How a GiST index stores a tsvector
A GIN index is an inverted index. It maps each lexeme to the list of rows that contain it. A GiST index cannot do that. For tsvector columns, GiST uses a signature, which is a fixed-size bit string that summarizes a document.
- Each lexeme in the document is hashed to one bit position.
- That bit is set in the document's signature.
- Leaf entries hold one signature per row. Internal tree pages hold the bitwise OR of the signatures below them.
A query is converted into a signature the same way. The index descends only into pages whose signature contains all the bits the query requires.
Different lexemes can hash to the same bit, so a signature can match a document that does not contain the term. This makes the index lossy. It can return false positives, but it never misses a real match.
Creating a GiST index
The syntax matches GIN with a different access method:
CREATE INDEX articles_search_gist ON articles USING gist (search);Queries do not change. The planner picks whichever index it estimates to be cheapest, so the @@ filter and ts_rank query from earlier chapters work as written.
From PostgreSQL 13 you can set the signature length in bytes with the siglen option. The default is 124 bytes, and the maximum is 2024 bytes.
CREATE INDEX articles_search_gist_256
ON articles USING gist (search tsvector_ops (siglen = 256));A longer signature has fewer hash collisions, so there are fewer false positives to recheck. The cost is a larger index and more I/O per page. A shorter signature does the opposite.
Seeing the recheck in a plan
On a small table the planner often prefers a sequential scan whatever indexes exist. To see how a GiST index behaves, discourage the sequential scan for one session:
SET enable_seqscan = off;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'full text search');
RESET enable_seqscan;Look for these in the plan:
- An index condition on
search, for exampleIndex Cond: (search @@ ...)orRecheck Cond. Rows Removed by Index Recheck. If this count is high compared with the rows returned, many signature collisions are being filtered out. Try a largersiglen.
Turning off enable_seqscan is a diagnostic tool. Do not leave it off in production.
GiST compared with GIN
| Aspect | GIN | GiST (signature) |
|---|---|---|
| Structure | Lexeme to list of rows | Fixed-size signature per row, in a tree |
| Lossy | No for `tsvector` | Yes, rows need a recheck |
| Lookup speed | Faster, roughly 3 times by the PostgreSQL documentation's estimate | Slower |
| Build time | Slower | Faster |
| Update cost | Higher, softened by the fast-update pending list | Lower |
| Index size | Usually larger on text-heavy data | Usually smaller |
| Scaling with vocabulary | Handles very large vocabularies well | Degrades as distinct lexemes grow |
The vocabulary point matters most. As the number of distinct lexemes grows, more of them share bits and signatures fill up with set bits. The false-positive rate rises, and so does the number of heap rows fetched and rechecked. The PostgreSQL documentation suggests GiST works well up to about 100,000 distinct lexemes and that GIN is better beyond that. Treat this as a rough guide and measure your own data.
Lexeme counts depend on your content. Use ts_stat from the debugging chapter to count distinct lexemes:
SELECT count(*) AS distinct_lexemes
FROM ts_stat('SELECT search FROM articles');When GiST is the better choice
- Write-heavy tables. If rows are inserted or updated constantly and queries are modest, GiST's lower maintenance cost can win. GIN's pending list reduces insert cost, but its flush work can still cause latency spikes.
- Small or medium vocabularies. Examples are product names, tags, or short records, where the distinct-lexeme count stays low.
- Index build time or size matters. Rebuilding a GiST index is usually quicker.
- One index for several operators. The
pg_trgmextension offersgist_trgm_ops, and GiST is the only one of the two that supports nearest-neighbor ordering for trigram distance.
For a mostly-read search over a large document collection, such as articles, wikis, or tickets, GIN remains the safer default.
GiST with pg_trgm
GiST is also the index that lets PostgreSQL sort by similarity directly from the index. This is covered in the typo-tolerance chapter, but the shape is short:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm_gist
ON articles USING gist (title gist_trgm_ops);
SELECT id, title
FROM articles
ORDER BY title <-> 'postgress'
LIMIT 5;The <-> operator returns a distance. Because GiST can return rows in distance order, the planner can stop after five rows without sorting every match. A GIN trigram index cannot do this. It can filter with % or LIKE, but ordering by distance needs a separate sort.
Common mistakes
- Expecting identical performance after switching. A GiST index returns the same rows as GIN for
@@, but the cost profile differs. Compare withEXPLAIN (ANALYZE, BUFFERS)on realistic data, not a toy table. - Forgetting that both indexes can coexist. Creating both makes writes slower and wastes space, and the planner uses only one per query. Pick one for the column unless you have measured a reason.
- Using a very short
siglento save space. The saved space is paid back in heap fetches. - Indexing the wrong expression. If you index
to_tsvector('english', body)directly rather than a stored column, the query must repeat the same expression and configuration exactly. The stored generated column from earlier chapters avoids this.
Exercise
A table has 3 million documents and about 800,000 distinct lexemes. It is searched constantly and updated rarely. Which index would you start with, and what in EXPLAIN (ANALYZE) output would tell you a GiST index is performing badly?
Show answer
Start with GIN. The vocabulary is far above the roughly 100,000 distinct lexemes where GiST signatures saturate, and reads dominate, so GIN's faster lookups outweigh its slower updates. A badly performing GiST index shows a large Rows Removed by Index Recheck relative to rows returned, plus many buffer reads from fetching candidate rows. Raising siglen reduces false positives, but GIN is the better fit here.