Sub topic 12
Indexing with GIN
Assume you know basic SELECT, WHERE, and ORDER BY statements, and that you can create PostgreSQL tables and indexes. This chapter assumes that tsvector, tsquery, and the @@ operator are familiar.
A full-text query can scan every document, but that becomes slow as a table grows. A GIN index stores the lexemes found in each tsvector. PostgreSQL can use those stored lexemes to find matching rows without checking every document.
Create a searchable column
A generated column keeps the search document synchronized with the source columns. The following example gives title terms weight A and body terms weight B.
CREATE TABLE articles (
id bigserial PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', body), 'B')
) STORED
);
CREATE INDEX articles_search_gin_idx
ON articles USING GIN (search);STORED means PostgreSQL calculates and saves the tsvector value whenever a row is inserted or updated. The index is built over that saved value.
Use the index in a query
Write the search condition directly against the indexed column.
SELECT a.id,
a.title,
ts_rank(a.search, q.query) AS rank
FROM articles AS a
CROSS JOIN (
SELECT websearch_to_tsquery('english', 'full text search') AS query
) AS q
WHERE a.search @@ q.query
ORDER BY rank DESC
LIMIT 10;The @@ condition produces candidate rows through the GIN index. PostgreSQL then fetches those rows, calculates their rank, sorts them, and returns the limit.
Check the query plan
Use EXPLAIN to verify whether PostgreSQL chooses the index.
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM articles
WHERE search @@ websearch_to_tsquery('english', 'full text');Look for a Bitmap Index Scan on articles_search_gin_idx, often followed by a Bitmap Heap Scan. PostgreSQL may choose a sequential scan for a small table or a query that matches most rows. That choice is normal. ANALYZE articles; updates statistics after loading substantial data.
GIN indexes speed up reads but add work to inserts and updates because index entries must change. Autovacuum helps clean obsolete entries. If write latency or index maintenance becomes a problem, measure it with EXPLAIN (ANALYZE, BUFFERS) and PostgreSQL monitoring before changing GIN settings.
Exercise
Why can an EXPLAIN plan use a sequential scan even when a GIN index exists?
Show answer
PostgreSQL estimates that scanning the table is cheaper, commonly because the table is small or the query matches many rows.