SQL · Module 13 · Lesson 71 min read

Full-Text Search

Why not just ILIKE '%word%'?

  • Can't handle word forms (run vs running, grocery vs groceries)
  • No relevance ranking
  • Slow on big tables without special indexes

The two building blocks

  • tsvector – a document processed into normalized words (lexemes) with positions to_tsvector('english', 'Weekly groceries at the market') → 'groceri':2 'market':5 'week':1 (stop words like "at", "the" are removed; words are stemmed)
  • tsquery – the search query
    • to_tsquery('english', 'grocery & market') – AND &, OR |, NOT !, prefix groc:*
    • plainto_tsquery('english', 'weekly groceries') – plain text, words ANDed
    • websearch_to_tsquery('english', '"monthly bill" -internet') ✅ Google-like syntax for search boxes

Matching

tsvector @@ tsquery → true/false

Ranking

  • ts_rank(vector, query) – higher = more relevant → ORDER BY rank DESC
  • setweight(vector, 'A') – make some fields count more (title A, note B)

Highlighting

ts_headline('english', text, query) → Weekly <b>groceries</b>…

Making it fast ⭐

  1. Store the vector in a generated column:
SQL
ALTER TABLE expenses ADD COLUMN search tsvector
  GENERATED ALWAYS AS (to_tsvector('english', title || ' ' || coalesce(note, ''))) STORED;
  1. Index it with GIN: CREATE INDEX … USING gin (search);

Languages

Configs like 'english', 'spanish', 'simple' (no stemming — good for names and mixed languages such as Nepali text). See \dF for available configs.

Fuzzy matching and typos

Full-text search doesn't fix typos ("grocries"). Combine it with pg_trgm similarity: similarity(title, 'grocries') > 0.3 or the % operator.

When to use a dedicated engine

Huge datasets, complex faceting or multi-language relevance tuning → Elasticsearch, Meilisearch, Typesense. For most apps, Postgres FTS is plenty.

Example

SQL
-- How documents and queries are normalized
SELECT to_tsvector('english', 'Weekly groceries at the market') AS doc,
       to_tsquery('english', 'grocery')                         AS query;
-- 'groceri':2 'market':5 'week':1 | 'groceri'

-- Searchable column + GIN index
ALTER TABLE expenses ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', title), 'A') ||
    setweight(to_tsvector('english', COALESCE(note, '')), 'B')
  ) STORED;
CREATE INDEX idx_expenses_search ON expenses USING gin (search);

-- Stemming: "grocery" finds "Groceries", "Weekly groceries", "Monthly groceries"
SELECT title FROM expenses
WHERE search @@ to_tsquery('english', 'grocery')
ORDER BY title;

-- Search box with Google-like syntax + ranking + highlighting
SELECT title, note,
       round(ts_rank(search, q)::numeric, 3) AS rank,
       ts_headline('english', title || ' — ' || COALESCE(note, ''), q,
                   'StartSel=[, StopSel=]')  AS highlighted
FROM expenses, websearch_to_tsquery('english', 'dinner OR birthday') AS q
WHERE search @@ q
ORDER BY rank DESC;
-- Dinner at Thamel (title + note both match → highest rank) …

-- Exclude words and prefix search
SELECT title FROM expenses WHERE search @@ websearch_to_tsquery('english', 'bill -internet');  -- electricity bills only
SELECT DISTINCT title FROM expenses WHERE search @@ to_tsquery('english', 'groc:*');         -- prefix

-- Typos: trigram similarity
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT DISTINCT title, round(similarity(title, 'grocries')::numeric, 2) AS sim
FROM expenses
WHERE similarity(title, 'grocries') > 0.3
ORDER BY sim DESC;
-- Groceries 0.58 | Weekly groceries 0.37 | Monthly groceries 0.35