Sub topic 16
Searching titles with full-text search
This chapter adds title search to the books table. It assumes you have the books table from the earlier chapters, with title declared NOT NULL, and a PostgreSQL 12 or newer server. The generated column used below needs version 12. You should also know what a B-tree index is. The chapter on indexing covers that.
Why LIKE is not enough
The obvious way to search titles is ILIKE:
SELECT title FROM books WHERE title ILIKE '%running%';This has three problems:
- It matches substrings, not words.
'%run%'also matches "Prune Your Garden". - It does not match word forms. A search for "run" misses "Running" and "Ran".
- A pattern with a leading
%cannot use an ordinary B-tree index, so PostgreSQL reads every row.
Full-text search fixes the first two by comparing normalized words. It fixes the third with an index type built for words.
The working model
Full-text search uses two types and one operator:
- A
tsvectoris a sorted list of normalized words (lexemes) with their positions. - A
tsqueryis a search expression made of lexemes and operators such as AND, OR, NOT, and phrase. - The
@@operator returns true when atsvectorsatisfies atsquery.
Both sides pass through the same text search configuration, such as english. A configuration splits text into tokens, drops stop words ("the", "are"), and reduces words to stems.
SELECT to_tsvector('english', 'The Dogs are running'); 'dog':2 'run':4"The" and "are" are gone, "Dogs" became dog, and "running" became run. The positions 2 and 4 still count the dropped words, which matters for phrase searches.
Adding a searchable column
Storing the tsvector next to the title avoids recomputing it on every query. A generated column keeps it in sync automatically:
ALTER TABLE books
ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;
CREATE INDEX books_search_idx ON books USING gin (search);Three details matter here:
- The configuration name is written out as
'english'. A generated column requires an immutable expression. The one-argument formto_tsvector(title)depends on thedefault_text_search_configsetting, which can change, so PostgreSQL rejects it. ADD COLUMN ... STOREDrewrites the whole table to compute the value for existing rows. That is quick for a personal library and a long exclusive lock on a very large table.- You cannot write to
searchdirectly. Updatingtitlerecomputes it.
A GIN (Generalized Inverted Index) maps each lexeme to the rows that contain it, like the index at the back of a book. It answers "which rows contain run?" without reading the table.
Querying
Load a few rows to try it. The ISBNs are made up:
INSERT INTO books (title, isbn13) VALUES
('The Running Man', '9780000000101'),
('Learning to Run Databases', '9780000000102'),
('Dogs of War', '9780000000103'),
('Running Man Returns', '9780000000104');
SELECT title
FROM books
WHERE search @@ websearch_to_tsquery('english', 'run');This returns the first, second, and fourth titles. The query run and the stored word running both reduce to the lexeme run.
Choosing a query parser
PostgreSQL has several functions that turn a string into a tsquery. They differ in how strictly they read user input.
| Function | Input style | Behavior on odd input |
|---|---|---|
| `plainto_tsquery` | Plain words | Joins all words with AND. Ignores operators. |
| `phraseto_tsquery` | Plain words | Requires the words adjacent and in order. |
| `websearch_to_tsquery` | Search-box syntax | Supports quotes, `or`, and `-`. Never raises a syntax error. |
| `to_tsquery` | Strict operator syntax | Raises an error on malformed input. Supports prefix `:*`. |
For text typed by a user, use websearch_to_tsquery. It accepts these forms:
-- both words, any order
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', 'running man');
-- an exact phrase
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', '"running man"');
-- exclude a word
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', 'run -databases');
-- either word
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', 'dogs or databases');The -databases query returns the two "Running Man" titles and drops "Learning to Run Databases".
Prefix matching
Search-as-you-type needs prefixes. Only to_tsquery supports them:
SELECT title FROM books
WHERE search @@ to_tsquery('english', 'data:*');This matches "Databases". The prefix applies to the stored stem, so a prefix like databa:* is safer than a long one that might extend past the stem. Passing raw user input to to_tsquery is risky because stray punctuation raises an error. Clean the input first or build the query in application code.
Ranking and highlighting
A match is yes or no. To order results by relevance, use ts_rank:
SELECT title,
ts_rank(search, q) AS rank,
ts_headline('english', title, q, 'StartSel=[, StopSel=]') AS snippet
FROM books,
websearch_to_tsquery('english', 'running man') AS q
WHERE search @@ q
ORDER BY rank DESC, title;Two things are worth knowing:
- Defining
qin theFROMclause computes the query once and lets you reuse it in three places. ts_headlinetakes the original text, not thetsvector. It re-parses the text for every row it returns, so call it only on the rows you display. Apply it after aLIMIT, for example in an outer query, when results are large.
Ranking on short titles has little to work with. Rank mostly reflects how often and how closely the terms occur, and a title has few words. For longer text you can weight parts with setweight, for example titles above descriptions.
Edge cases and gotchas
- Stop words vanish. Searching for "the" alone produces an empty query and matches nothing. PostgreSQL emits a notice that the query contains only stop words or no lexemes.
- Language matters. The
englishstemmer mangles titles in other languages. Use a configuration that matches the text, orsimple, which lowercases but does not stem or drop stop words. Names and foreign titles often search better withsimple. - Stemming surprises. Different words can share a stem. You can inspect what the parser does with
ts_debug('english', 'Running Man'). - Typos are not matched. Full-text search compares exact lexemes. For fuzzy matching, look at the
pg_trgmextension. - The index may be ignored on small tables. With four rows the planner prefers a sequential scan, which is correct. To confirm the index works, test on more data or run
SET enable_seqscan = off;in a session, thenEXPLAINthe query. Reset it afterward. Do not leave it off in an application. - Authors are not searchable here. A generated column can only use columns of its own row. To search authors too, you need a trigger-maintained column, a view, or a query that joins
authorsand builds the vector on the fly.
Verifying the index
Check that PostgreSQL uses the GIN index:
SET enable_seqscan = off;
EXPLAIN (ANALYZE)
SELECT title FROM books
WHERE search @@ websearch_to_tsquery('english', 'run');
RESET enable_seqscan;Look for a Bitmap Index Scan on books_search_idx node. A GIN index returns candidate rows through a bitmap, so you see a Bitmap Heap Scan above it. If you see Seq Scan, the planner chose not to use the index or the configurations do not match.
Exercise
A learner runs SELECT title FROM books WHERE search @@ websearch_to_tsquery('simple', 'running'); against the search column defined in this chapter, and a title "The Running Man" is not returned. Why, and how do they fix it?
Show answer
The search column was built with the english configuration, which stems "Running" to the lexeme run. The simple configuration keeps the word as running, so the query lexeme running does not equal the stored run. The fix is to use 'english' in the query. If exact-word matching is wanted instead, rebuild the column with 'simple' and query with 'simple'.
Exercise
Write a query that returns books whose titles contain the phrase "running man" and shows the title with matches wrapped in [ and ].
Show answer
SELECT tsheadline('english', title, q, 'StartSel=[, StopSel=]') AS snippet FROM books, websearchto_tsquery('english', '"running man"') AS q WHERE search @@ q;