← Back to SQL, page 20

sql-0384 · Medium mid

How does basic full-text search work in PostgreSQL, compared with LIKE?

to_tsvector turns text into normalised lexemes (stemmed words without stop words), and to_tsquery builds a search expression; @@ tests a match. Unlike LIKE '%word%', it matches word forms such as 'running' for 'run', ranks results and can use a GIN index. Store a generated tsvector column and index it for speed.

Full answer
sql
SELECT to_tsvector('english', 'The cats are running')::text AS lexemes;
lexemes
'cat':2 'run':4

The English configuration dropped the stop words 'The' and 'are', stemmed 'cats' to 'cat' and 'running' to 'run', and recorded word positions.

sql
SELECT to_tsvector('english', 'The cats are running') @@ to_tsquery('english', 'cat & run') AS matches;
matches
true

The query cat & run matches although neither word appears literally. A LIKE search for '%cat%run%' would also match 'concatenate rune', and cannot use a B-tree index.

Production setup:

text
ALTER TABLE articles ADD COLUMN search tsvector
  GENERATED ALWAYS AS (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,''))) STORED;
CREATE INDEX articles_search ON articles USING gin (search);
SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'cat running')
ORDER BY ts_rank(search, websearch_to_tsquery('english', 'cat running')) DESC;

The DDL above is illustrative and was not run here. SQLite provides full-text search through the FTS5 module instead.

Key points

  • to_tsvector normalises text into lexemes
  • to_tsquery and @@ match word forms
  • GIN indexes speed up searches
  • Stored generated tsvector columns keep it in sync
  • LIKE matches substrings, not words

Common mistakes

  • Using LIKE '%x%' for search over large text
  • Mixing text search configurations between indexing and querying

Follow-ups

  • How would you rank results?
  • When would an external search engine be better?

Tips

  • Show the lexemes