Sub topic 3
Storing the tsvector in a generated column
This chapter assumes PostgreSQL 12 or later, familiarity with CREATE TABLE and CREATE INDEX, and basic use of to_tsvector and the @@ operator. Recomputing to_tsvector on every query is slow, so you will store the vector in the table and index it.
Storing a weighted tsvector
A stored generated column computes its value on write and keeps it in sync automatically.
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
);The weight A marks title lexemes and B marks body lexemes. Ranking functions use these weights later.
GIN and GiST indexes
GIN (Generalized Inverted Index) maps each lexeme to the rows that contain it. It is the usual choice for full-text search.
CREATE INDEX articles_search_idx ON articles USING gin (search);GiST (Generalized Search Tree) is the alternative. It builds smaller indexes and updates faster, but queries are slower and results are lossy, so PostgreSQL rechecks matches against the heap. Choose GiST for write-heavy tables where lookup speed matters less.
Dictionaries and configurations
Dictionaries decide which words are kept. Stop words such as "the" are dropped, and stemming reduces "running" to "run". Synonym and thesaurus dictionaries map terms to preferred forms. A text search configuration chains these dictionaries together for one language.
Custom configuration with unaccent
The unaccent extension removes accents, so "café" and "cafe" match.
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE TEXT SEARCH CONFIGURATION my_english (COPY = english);
ALTER TEXT SEARCH CONFIGURATION my_english
ALTER MAPPING FOR hword, hword_part, word
WITH unaccent, english_stem;Debugging with ts_debug, ts_stat and EXPLAIN
SELECT alias, token, dictionaries, lexemes
FROM ts_debug('english', 'The foxes were running');
SELECT word, ndoc
FROM ts_stat('SELECT search FROM articles')
ORDER BY ndoc DESC
LIMIT 5;
EXPLAIN SELECT id FROM articles
WHERE search @@ websearch_to_tsquery('english', 'full text search');ts_debug shows how each token was parsed. ts_stat lists the most frequent lexemes. EXPLAIN confirms that the GIN index is used on tables large enough to need it.
Typo-tolerant search with pg_trgm
The pg_trgm extension compares strings by three-character groups, so it tolerates misspellings. It ignores stemming and stop words, so use it next to tsvector, not instead of it.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX articles_title_trgm_idx ON articles USING gin (title gin_trgm_ops);
SELECT title, similarity(title, 'postgre') AS score
FROM articles
WHERE title % 'postgre'
ORDER BY score DESC;Limitations and external engines
Built-in search handles many workloads on one server. Consider an external engine such as Elasticsearch or OpenSearch when you need large-scale faceting, advanced language analyzers, or search capacity that scales apart from the database.
Exercise
Exercise
Why does the articles table weight title lexemes as A and body lexemes as B?
Show answer
Ranking functions such as ts_rank give higher scores to A-weighted matches, so a word found in the title ranks above the same word found only in the body.