Full-Text Search Fundamentals

Learn how search engines tokenize, index and rank text, and how far PostgreSQL search can take you.

Intermediate · about 4 hours · difficulty 3/5

Learn first: Indexes and Query Performance

WHERE title LIKE '%phone%' cannot use a normal index, does not match "phones", and has no idea which result is most relevant. Full-text search solves this with a different data structure and a ranking model.

How search works

  • Analysis: text is split into tokens, lowercased, stripped of stop words and reduced to a root form (stemming: "running" becomes "run").
  • Inverted index: a map from each term to the documents containing it, so lookups are fast regardless of table size.
  • Relevance scoring: algorithms like BM25 rank documents higher when the term is rare across the corpus but frequent in the document.
  • Extras users expect: typo tolerance (fuzzy matching), prefix search for autocomplete, highlighting, facets and filters.

Start with your database

PostgreSQL's built-in search (tsvector, tsquery, GIN indexes, ts_rank) plus the pg_trgm extension for fuzzy matching handles product catalogs and docs sites with hundreds of thousands of rows well. MySQL has FULLTEXT indexes too. Keeping search in the database avoids a second system to sync.

When to add a search engine

Move to a dedicated engine when you need advanced relevance tuning, multi-language analysis, heavy faceting, very large corpora or search load that should not hit your primary database. Lightweight options like Meilisearch or Typesense are quick to adopt; Elasticsearch/OpenSearch cover the heavy end.

Keeping search in sync

The search index is a derived copy of your data. Update it from application events or a change-data-capture pipeline, and be able to rebuild it from scratch.

You are ready to move on when you can add ranked, stemmed search with a GIN index to a Postgres table and explain why it beats LIKE.

Key concepts

  • Tokenization and stemming
  • Inverted indexes
  • Relevance scoring and BM25
  • PostgreSQL tsvector and GIN
  • Fuzzy search with pg_trgm
  • Meilisearch and Typesense
  • Keeping the index in sync

Mini project

Add a search endpoint to a product catalog using Postgres full-text search with ranking, typo tolerance via pg_trgm and highlighted snippets.

Check yourself

What is an inverted index, and why can it answer a text query faster than scanning every row?

Free resources