Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 14 / Topic 9 of 10

Full-text search

LIKE '%laptop%' matches characters; full-text search matches language — it stems words, drops stopwords, ranks relevance. Two types do the work: to_tsvector digests a document, to_tsquery (and friends) expresses the search, @@ matches them:

SELECT to_tsvector('english', 'The Postgres books are deeply discounted') AS digested;
                  digested                   
---------------------------------------------
 'book':3 'deepli':5 'discount':6 'postgr':2
(1 row)

(Stemmed, positioned, stopwords gone — "books" became book, so searches for either match.) Against products, with ranking:

SELECT name,
       ts_rank(to_tsvector('english', name), query) AS rank
FROM products,
     to_tsquery('english', 'laptop | postgres') AS query
WHERE to_tsvector('english', name) @@ query
ORDER BY rank DESC, name;
        name        |    rank     
--------------------+-------------
 Laptop Air 13      | 0.030396355
 Laptop Pro 14      | 0.030396355
 Postgres Deep Dive | 0.030396355
(3 rows)

| is OR, & AND, <-> adjacency; plainto_tsquery / websearch_to_tsquery parse human input safely. Production-shape: store the tsvector as a generated column (Part 10's tool!) and GIN-index it — searched text digested once, matched fast. Postgres won't replace a dedicated search cluster at web scale, but for "search our catalogue/tickets/docs" it removes an entire extra system.

🧪 Quick quiz — answer from memory, then check.

  1. What does to_tsvector do to "The Postgres books"?
  2. Which operator matches a tsvector against a tsquery?
Show the answers
  1. Drops "The" (a stopword), stems "books" down to book, and records positions: 'book':3 'postgr':2-style.
  2. @@.

Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.

Search the guide