Skip to content

Lesson 24 of 29Postgres in production

Full-Text Search in the Database

Build real search inside Postgres with tsvector, GIN, ranking, snippets and trigrams, practice it with SQLite FTS5, and know when to move to a search engine.

16 min read0/5 questions

The product team asks for a search box on the catalogue. The first version ships in ten minutes: WHERE name ILIKE '%' || $1 || '%'. A month later the bug reports arrive. Searching "laptops" finds nothing because the product says "laptop". Searching "run" returns a book about pruning code. The best match is on page three because nothing is ranked. And on the big products table every search is a full scan. You do not need Elasticsearch yet. Postgres has a real full-text search engine built in, and for most catalogues, help centres and admin tools it is enough. This lesson shows how it works, how to build it properly, and where its limits are. The general theory of inverted indexes and BM25 lives in Search and Inverted Indexes; here you build it in SQL.

LIKE '%term%' has three problems, and only one of them is speed.

  • No index. A B-tree can only help a pattern anchored at the start, such as LIKE 'lap%'. A leading wildcard scans every row.
  • No language. It matches characters, not words. "laptops" does not find "laptop", and "run" happily matches "prune".
  • No ranking. A row either matches or it does not. A product with "laptop" in its name and one that mentions it once in a footnote come back in arbitrary order.

You can see the first two on the course dataset. The block gives each product a description, then searches with LIKE and with SQLite's built-in full-text engine, FTS5, which works like Postgres's version in the ways that matter here:

Pythonlike_vs_fts.py
from shopdb import connect, showdb = connect() # Give the catalogue some text to search.db.executescript("""ALTER TABLE products ADD COLUMN description TEXT NOT NULL DEFAULT '';UPDATE products SET description = CASE id WHEN 1 THEN 'A 14 inch laptop for developers who run containers and compile large projects.' WHEN 2 THEN 'A light laptop for travel, with all-day battery and a quiet fanless design.' WHEN 3 THEN 'Seven ports in one hub: HDMI, ethernet and power delivery for your laptop.' WHEN 4 THEN 'Tactile brown switches. Typing feels great during long coding sessions.' WHEN 5 THEN 'A quiet wireless mouse that runs for months on one battery.' WHEN 6 THEN 'Wireless headphones that block noise on trains and in open offices.' WHEN 7 THEN 'A small wireless speaker for running playlists outdoors.' WHEN 8 THEN 'How databases, replication and stream processing really work.' WHEN 9 THEN 'Classic advice on writing code that is easy to change, and when to prune it.' WHEN 10 THEN 'How indexes work and how developers can make queries run faster.'END;""") print("LIKE '%run%' (note The Pragmatic Programmer, matched by 'prune'):")show(db, "SELECT id, name FROM products WHERE name LIKE '%run%' OR description LIKE '%run%'")print("LIKE '%laptops%':")show(db, "SELECT id, name FROM products WHERE description LIKE '%laptops%'") # An FTS5 index over the same rows, with an English stemmer.db.executescript("""CREATE VIRTUAL TABLE products_fts USING fts5( name, description, content='products', content_rowid='id', tokenize='porter unicode61');INSERT INTO products_fts (products_fts) VALUES ('rebuild');""") def search(q): print(f"\nMATCH {q!r}") show(db, """ SELECT p.id, p.name, round(bm25(products_fts, 10.0, 1.0), 2) AS score FROM products_fts JOIN products AS p ON p.id = products_fts.rowid WHERE products_fts MATCH ? ORDER BY score """, (q,)) search("run") # run, runs, running; not prunesearch("laptops") # stems to laptopsearch("wireless NOT speaker")search('"long coding"') # phrasesearch("develop*") # prefixsearch("name:laptop") # only the name column
Output
Press Run (⌘ Enter) to see what happens.

The stemmer reduced "runs" and "running" to "run" and "laptops" to "laptop", at index time and at query time, so they meet in the middle. bm25() ranks the results, and the weights 10.0, 1.0 make a match in the name worth ten times a match in the description. FTS5's bm25 returns lower-is-better scores, which is why the query sorts ascending.

How Postgres analyses text

Postgres turns a document into a tsvector: a sorted list of normalised words, called lexemes, with their positions. It turns a search into a tsquery: lexemes joined by & (and), | (or), ! (not) and <-> (followed by). The @@ operator asks whether a vector matches a query.

SELECT to_tsvector('english', 'The Runners were running quickly');
-- 'quick':5 'run':4 'runner':2
 
SELECT to_tsvector('english', 'The Runners were running quickly')
       @@ to_tsquery('english', 'run & quick');   -- true

The 'english' argument is a text search configuration: which parser, stop-word list and stemmer to use. Each step of the pipeline throws information away on purpose:

From text to tsvector
  1. The Runners were running quicklyraw document
  2. The | Runners | were | running | quicklyparser splits tokens
  3. the | runners | were | running | quicklylowercased
  4. runners | running | quicklystop words removed
  5. 'runner':2 'run':4 'quick':5stemmed, with positions

The parser finds tokens and their types: words, numbers, emails, URLs. Each type can be handled differently.

1/3

Two consequences follow. The same configuration must be used for documents and queries, or "running" in the document becomes run while the query looks for running. And language matters: an English stemmer mangles German, and no stemmer should touch product codes or surnames. Use the simple configuration (lowercase only, no stop words, no stemming) for those, and if your rows are in several languages, store each row's configuration in a regconfig column.

Building it properly in Postgres

Do not call to_tsvector inside every query. Store the vector in a generated column, weight the fields, and put a GIN index on it. A GIN index here is an inverted index: for each lexeme, the list of rows that contain it.

migrations/0060_product_search.sql
ALTER TABLE products ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(description, '')), 'B') ||
    setweight(to_tsvector('simple',  coalesce(sku, '')), 'A')
  ) STORED;
 
CREATE INDEX CONCURRENTLY products_search_idx ON products USING GIN (search);

Details that matter:

  • Two-argument to_tsvector only. The one-argument form depends on the default_text_search_config setting, so it is not immutable and cannot be used in a generated column or an index. If your query's expression does not match the index's, the index is silently skipped.
  • STORED, not virtual. Postgres 18 made virtual generated columns the default, but you cannot index a virtual generated column, so spell out STORED.
  • coalesce: to_tsvector of NULL is NULL, and NULL concatenated with anything is NULL, so one missing description would make the whole product unsearchable.
  • Weights A to D label where each lexeme came from, and ranking functions use them. The SKU uses simple, so KB-104 is not stemmed.
  • On an existing table, adding a stored generated column rewrites it. On a big table, add a plain tsvector column, fill it with a trigger and a batched backfill, as in Zero-Downtime Migrations.

GIN is the usual choice for search: fast lookups, slower updates. GiST indexes on tsvector are smaller and cheaper to update but lossy, so matches must be rechecked. Choose GiST only if write cost dominates.

Parsing user input safely

to_tsquery expects query syntax. Pass it what a user typed and it fails:

SELECT to_tsquery('english', 'usb-c hub');
-- ERROR:  syntax error in tsquery
 
SELECT websearch_to_tsquery('english', '"running shoes" -kids or trail');
-- 'run' <-> 'shoe' & !'kid' | 'trail'

Use websearch_to_tsquery for search boxes. It accepts the syntax people already know from web search engines (quotes for phrases, or, a leading - to exclude) and never raises a syntax error. plainto_tsquery ANDs every word together and ignores operators; phraseto_tsquery requires the words in order. Keep to_tsquery for queries your own code builds, such as a prefix search 'lapt:*' for autocomplete.

A query made only of stop words, such as "the", becomes an empty tsquery that matches nothing. Decide what your UI shows for that: probably the same as an empty search.

SQLite has the same problem in a different shape. An FTS5 MATCH string is query syntax too, and the usual fix is to quote each word. This block also keeps the index in sync with triggers and shows the result-page helpers:

Pythonfts_sync_and_snippets.py
from shopdb import connect, showdb = connect() db.executescript("""ALTER TABLE products ADD COLUMN description TEXT NOT NULL DEFAULT '';UPDATE products SET description = CASE id WHEN 1 THEN 'A 14 inch laptop for developers who run containers and compile large projects.' WHEN 3 THEN 'Seven ports in one hub: HDMI, ethernet and power delivery for your laptop.' WHEN 5 THEN 'A quiet wireless mouse that runs for months on one battery.' WHEN 7 THEN 'A small wireless speaker for running playlists outdoors.' ELSE ''END; CREATE VIRTUAL TABLE products_fts USING fts5( name, description, content='products', content_rowid='id', tokenize='porter unicode61');INSERT INTO products_fts (products_fts) VALUES ('rebuild'); -- Keep the index in sync with the table it points at.CREATE TRIGGER products_fts_ai AFTER INSERT ON products BEGIN INSERT INTO products_fts (rowid, name, description) VALUES (NEW.id, NEW.name, NEW.description);END;CREATE TRIGGER products_fts_ad AFTER DELETE ON products BEGIN INSERT INTO products_fts (products_fts, rowid, name, description) VALUES ('delete', OLD.id, OLD.name, OLD.description);END;CREATE TRIGGER products_fts_au AFTER UPDATE ON products BEGIN INSERT INTO products_fts (products_fts, rowid, name, description) VALUES ('delete', OLD.id, OLD.name, OLD.description); INSERT INTO products_fts (rowid, name, description) VALUES (NEW.id, NEW.name, NEW.description);END;""") db.execute("""INSERT INTO products (name, category_id, price_cents, description)VALUES ('Trail Running Watch', 5, 24900, 'GPS watch that tracks every run and long hike.')""") show(db, """SELECT p.name, highlight(products_fts, 0, '[', ']') AS name_hit, snippet(products_fts, 1, '[', ']', '...', 6) AS excerptFROM products_fts JOIN products AS p ON p.id = products_fts.rowidWHERE products_fts MATCH 'run'ORDER BY bm25(products_fts, 10.0, 1.0)LIMIT 3""") # Raw user input is query syntax, so it can be invalid.user_input = 'usb-c hub'try: db.execute("SELECT rowid FROM products_fts WHERE products_fts MATCH ?", (user_input,)).fetchall()except Exception as exc: print(f"\n{user_input!r} as raw syntax fails: {exc}") def to_fts_query(text): # Quote every word, so the input is treated as plain terms ANDed together. words = text.replace('"', ' ').split() return " ".join(f'"{w}"' for w in words) safe = to_fts_query(user_input)print("safe query:", safe)show(db, """SELECT p.name FROM products_fts JOIN products AS p ON p.id = products_fts.rowidWHERE products_fts MATCH ?""", (safe,))
Output
Press Run (⌘ Enter) to see what happens.

The new watch was searchable the moment it was inserted, because the trigger wrote it into the index in the same transaction. An external-content table like this one (content='products') stores only the index, not a second copy of the text, which is why it needs those triggers. Forget the update trigger and the index slowly drifts away from the table.

Ranking and snippets without melting the database

Postgres ranks with ts_rank, which weighs how often the query's lexemes appear and in which weighted fields, and ts_rank_cd, which also rewards matching words that sit close together. ts_headline builds the highlighted excerpt for a results page.

SELECT id, name,
       ts_headline('english', description, q, 'MaxFragments=1, MaxWords=20') AS excerpt
FROM (
  SELECT id, name, description, q, ts_rank(search, q) AS rank
  FROM products, websearch_to_tsquery('english', $1) AS q
  WHERE search @@ q
  ORDER BY rank DESC
  LIMIT 20
) AS top
ORDER BY rank DESC;

The shape of that query is deliberate, and it is the part interviewers and reviewers look for:

One search request inside Postgres
AppGIN indexTableTop 20search @@ qcandidate rowsORDER BY rank LIMIT 20ts_headline on 20 rows

The index looks up each lexeme's row list and intersects them. This part is fast even on millions of rows.

1/4

Ranking quality has limits too. ts_rank is not BM25: it has no idea how rare a word is across the whole table, so "laptop" and "fanless" count the same. You can normalise for document length with its optional third argument, and many teams mix in business signals, such as popularity or recency, in the ORDER BY. If relevance becomes a product feature in its own right, that is a sign to look at a search engine or one of the Postgres extensions that add BM25 (check that your host supports it).

Typos, substrings and accents: pg_trgm and unaccent

Full-text search matches whole words. It does not forgive "labtop", and it cannot find "book" inside "MacBook". The pg_trgm extension fills that gap. It splits strings into three-character chunks (trigrams) and compares how many two strings share:

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX products_name_trgm ON products USING GIN (name gin_trgm_ops);
 
SELECT similarity('labtop pro', 'Laptop Pro 14');        -- a score from 0 to 1
 
SELECT name FROM products
WHERE name % 'labtop pro'                                -- similar enough
ORDER BY similarity(name, 'labtop pro') DESC
LIMIT 5;
 
SELECT name FROM products WHERE name ILIKE '%book%';     -- now uses the trigram index

The % operator uses a threshold (pg_trgm.similarity_threshold, 0.3 by default). A trigram GIN index also accelerates LIKE, ILIKE and regular expressions with leading wildcards, as long as the pattern has at least three characters. A common design is to run the full-text query first and fall back to trigram similarity when it returns nothing: the "did you mean" path.

The unaccent extension strips accents so "cafe" matches "café". Its function is not marked immutable, so you cannot use it directly in an index; the usual approaches are an immutable wrapper function or a custom text search configuration that includes the unaccent dictionary. Check the docs for the pattern your Postgres version recommends.

When to graduate to a search engine

Postgres search stays a good choice while the data is in the low millions of rows, relevance needs are simple, and search traffic does not compete with your writes. Move to OpenSearch or Elasticsearch, Typesense or Meilisearch when you need facets with counts, synonyms and per-field relevance tuning, typo tolerance across the whole query, or search load that would slow down your primary database. The cost is a second datastore that must be kept in sync, usually through an outbox table or change data capture, and that is often eventually consistent. Search and Inverted Indexes covers that architecture.

Meaning-based search is the other direction. With the pgvector extension you store embeddings next to the rows and find products that mean "something to block noise on a flight" even with no shared words. Many teams run hybrid search: full-text and vector queries in parallel, merged with a method such as reciprocal rank fusion. RAG and Embeddings covers how embeddings work.

Predict the outputPython

This FTS5 table uses the default tokenizer, with no stemmer. What does it print?

from shopdb import connect
db = connect()
db.executescript("""
CREATE VIRTUAL TABLE notes USING fts5(body);
INSERT INTO notes (body) VALUES ('running shoes'), ('shoe rack'), ('the runner');
""")
count = lambda q: db.execute("SELECT count(*) FROM notes WHERE notes MATCH ?", (q,)).fetchone()[0]
print(count("shoe"), count("run*"))
Need a nudge? Hints walk you through it.
Quick check
Your search endpoint runs WHERE search @@ to_tsquery('english', $1) and logs show 500 errors for some searches. What is the best fix?
Need a nudge? A hint rules out a wrong answer.
Quick check
There is a GIN index on to_tsvector('english', body). Which query cannot use it?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Order the steps of an efficient search query in Postgres.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each need to the Postgres tool.

Choose an item, then its match on the other side.
Key terms
tsvector
Postgres's searchable form of a document: a sorted list of normalised lexemes with positions and optional weights.
tsquery
A parsed search: lexemes combined with & (and), | (or), ! (not) and <-> (followed by).
lexeme
A normalised word after lowercasing and stemming, such as run for running.
stemming
Cutting words to a common root with language rules, so different forms of a word match each other.
websearch_to_tsquery
Turns free text from a search box into a tsquery, supporting quotes, or and -, without ever raising a syntax error.
pg_trgm
A Postgres extension that compares strings by shared three-character chunks, for typo tolerance and indexed substring search.
FTS5
SQLite's built-in full-text search engine: a virtual table queried with MATCH and ranked with bm25().