PostgreSQL Full-Text Search
LIKE '%word%' finds exact substrings, but real search needs more: "running" should match "run", small words such as "the" should be ignored, and the best matches should come first. PostgreSQL has a complete full-text search engine built in.
Documents and queries
Full-text search works with two special types:
tsvector: a document processed into lexemes (normalised word stems) with their positions.tsquery: a search query made of lexemes combined with&(and),|(or),!(not) and<->(followed by).
SELECT to_tsvector('english', 'The dragons were counting their tiny treasures') AS document;
SELECT to_tsquery('english', 'dragon & treasure') AS query; document
-------------------------------------------
'count':4 'dragon':2 'tini':6 'treasur':7
(1 row)
query
----------------------
'dragon' & 'treasur'
(1 row)
The english configuration lower-cases words, removes stop words ("the", "were", "their") and reduces words to stems ("dragons" → "dragon", "counting" → "count").
Matching with @@
The @@ operator tests whether a document matches a query:
SELECT to_tsvector('english', 'Running a detective agency by the sea') @@ to_tsquery('english', 'run & detective') AS match_1,
to_tsvector('english', 'Running a detective agency by the sea') @@ to_tsquery('english', 'run & space') AS match_2; match_1 | match_2
---------+---------
t | f
(1 row)
Searching the books
Let's build a searchable text from each book's title and tags and look for books about the sea or space:
SELECT title
FROM books
WHERE to_tsvector('english', title || ' ' || array_to_string(tags, ' '))
@@ to_tsquery('english', 'sea | space')
ORDER BY title; title
--------------------
Harbor Lights
Moon Socks
Murder at Low Tide
Signal from Kepler
The Last Orbit
(5 rows)
User input: websearch_to_tsquery
to_tsquery expects its special syntax and fails on ordinary text. For a search box, use plainto_tsquery (all words must match) or websearch_to_tsquery, which understands quotes, or and a minus sign like a web search engine:
SELECT websearch_to_tsquery('english', 'detective -courtroom') AS q1,
websearch_to_tsquery('english', '"low tide" or maps') AS q2,
plainto_tsquery('english', 'learning SQL calmly') AS q3; q1 | q2 | q3
-------------------------+--------------------------+--------------------------
'detect' & !'courtroom' | 'low' <-> 'tide' | 'map' | 'learn' & 'sql' & 'calm'
(1 row)
A stored search column with ranking
Computing to_tsvector for every row on every search is slow. A generated column keeps the vector up to date automatically, and a GIN index makes searches fast. setweight marks title words as more important (A) than tags (B), and ts_rank orders results by relevance.
A generated column may only use immutable functions (functions whose result depends only on their arguments). array_to_string is not marked immutable, so we wrap it in a tiny SQL function that is:
CREATE FUNCTION tags_text(text[]) RETURNS text
LANGUAGE sql IMMUTABLE
RETURN array_to_string($1, ' ');
ALTER TABLE books ADD COLUMN search tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', tags_text(tags)), 'B')
) STORED;
CREATE INDEX books_search_idx ON books USING gin (search);
SELECT title, tags, round(ts_rank(search, q)::numeric, 3) AS rank
FROM books, websearch_to_tsquery('english', 'kitchen or family') AS q
WHERE search @@ q
ORDER BY rank DESC, title;CREATE FUNCTION
ALTER TABLE
CREATE INDEX
title | tags | rank
-------------------+-------------------+-------
Starlight Kitchen | {food,family} | 0.426
Harbor Lights | {family,sea} | 0.122
Paper Lanterns | {family,festival} | 0.122
The Salt Road | {travel,family} | 0.122
(4 rows)
Starlight Kitchen comes first: "kitchen" is in its title (weight A) and "family" in its tags. The other books only match a tag.
Highlighting matches
ts_headline returns the text with the matching words marked, which is how search pages show snippets:
SELECT ts_headline('english', title, to_tsquery('english', 'tide | witness'),
'StartSel=[, StopSel=]') AS headline
FROM books
WHERE to_tsvector('english', title) @@ to_tsquery('english', 'tide | witness'); headline
----------------------
Murder at Low [Tide]
The Quiet [Witness]
(2 rows)
| Function | Use |
|---|---|
to_tsvector(config, text) |
text → searchable document |
to_tsquery / plainto_tsquery / websearch_to_tsquery |
text → query |
doc @@ query |
does it match? |
ts_rank, ts_rank_cd |
relevance score |
ts_headline |
highlighted snippet |
setweight(vector, 'A'…'D') |
mark importance of parts |
Tip: Full-text search is language-aware. Use the configuration that matches your text (
'english','german','simple'for no stemming) and use the same configuration for documents and queries.
Test yourself
What does to_tsvector('english', ...) do with the word "the"?
- Keeps it
- Removes it as a stop word
- Turns it into 'th'
- Raises an error
Which operator tests whether a tsvector matches a tsquery?
- =
- LIKE
- @@
- ~
Which function is best for turning raw search-box text into a query?
- to_tsquery
- websearch_to_tsquery
- to_tsvector
- ts_rank