Sub topic 13
GiST as an Alternative Index
Assume you know how to store a weighted tsvector in an articles.search column. This chapter compares a GiST index with the usual GIN index for PostgreSQL full-text search.
How a GiST full-text index works
GiST, or Generalized Search Tree, is an index framework for data types that need specialized search strategies. For a tsvector, a GiST index stores a compact signature that represents the lexemes in each document.
Create one with USING gist:
CREATE INDEX articles_search_gist_idx
ON articles USING gist (search);A search can then use the index for the @@ operator:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, title
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'full text search');The query planner decides whether the index is cheaper than a sequential scan. Test with realistic data, because an index is not automatically faster for every table or query.
GiST and GIN trade-offs
GiST signatures are lossy. A signature can say that a document might match, but PostgreSQL must recheck the document's actual tsvector. This recheck prevents incorrect results, but it adds work when many rows are false positives.
GIN stores an inverted mapping from lexemes to rows. It usually gives faster full-text lookups, especially when documents contain many distinct terms. GiST can use less space and may be easier to combine with other GiST-supported data types or index strategies.
| Property | GIN | GiST |
|---|---|---|
| Typical full-text lookup speed | Usually faster | Often slower because of rechecks |
| Index representation | Lexeme-to-row postings | Lossy signatures |
| False-positive rechecks | No, for normal matching | Yes |
| Update and index size trade-off | Can be larger and costlier to update | Often smaller and more flexible |
You can increase the GiST signature length when false positives are expensive:
CREATE INDEX articles_search_gist_wide_idx
ON articles
USING gist (search gist_tsvector_ops(siglen = 256));A larger signature usually reduces false positives, but it increases index size and may increase maintenance cost. The default signature length is often a reasonable starting point. Do not create both GIN and GiST indexes without measuring a real need, because every additional index consumes storage and slows writes.
Exercise
Why can a GiST full-text query inspect rows that do not actually match the tsquery?
Show answer
GiST uses lossy signatures. The index identifies possible matches, and PostgreSQL rechecks each candidate row against the full tsvector.