Full-Text Search

Difficulty: Intermediate

Question

Why is a query like WHERE title LIKE '%keyword%' slow on a large table, and what would you use instead?

Answer

A leading wildcard ('%keyword%') makes a normal B-tree index useless, because a B-tree is sorted by the beginning of the string and the database cannot know where in that sorted order a value containing "keyword" somewhere in the middle would sit. It has to read every row and test each string, which is a full table scan. The fix is an index built for substring or word search: a trigram index (PostgreSQL pg_trgm) for substring matching, or a full-text index (tsvector with GIN, MySQL FULLTEXT, or a search engine like Elasticsearch/OpenSearch) for word-based search.

Why the B-tree cannot help

Think of a B-tree on title like a phone book sorted by name.

  • LIKE 'Data%' is a prefix search: jump to "Data" and read forward until the prefix stops matching. Fast.
  • LIKE '%Data%' could match "Big Data Engineer" or "Database Admin". Those are scattered across the entire sorted order, so there is nowhere to jump to.

In PostgreSQL, even prefix LIKE only uses a plain B-tree when the column uses the C collation, or when the index is created with text_pattern_ops. ILIKE and lower(title) LIKE need an index on the matching expression.

Option 1: trigram indexes for substring search

pg_trgm splits text into three-character chunks. "data" becomes trigrams like "dat" and "ata". A GIN index over those trigrams lets PostgreSQL find candidate rows containing all the trigrams of the search term, then recheck them. It supports LIKE, ILIKE and regex, and similarity search for typos. It is best for short fields like names, company titles and SKUs. Search terms shorter than three characters get little help.

Option 2: full-text search for word search

Full-text search tokenises text into normalised words (lexemes), removes stop words, and stems words so "running", "runs" and "run" match. It builds an inverted index: word to list of rows.

ApproachGood atWeak at
LIKE '%x%' (no index)Tiny tables, ad-hoc queriesAnything large
pg_trgm GINSubstrings, fuzzy and typo matchingLong documents, relevance ranking
tsvector GINWord matching, stemming, rankingPartial-word matches, Indian names and mixed scripts without tuning
Elasticsearch / OpenSearchRelevance, facets, synonyms, autocomplete at scaleExtra system to run and keep in sync

What real products do

A job board searching "react developer bangalore" across lakhs of listings wants ranking, stemming and filters, so it uses full-text search in PostgreSQL for moderate scale or a dedicated engine for large scale. Searching a company name in an admin panel is a trigram job. MySQL offers FULLTEXT indexes queried with MATCH ... AGAINST.

Common mistakes

  • Wrapping the column in a function (lower(title)) without an expression index, which also forces a scan.
  • Using to_tsvector inside the WHERE clause without a matching index or stored generated column.
  • Expecting full-text search to find partial words like "dev" inside "developer"; that needs prefix queries (dev:*) or trigrams.
  • Running a separate search engine without a reliable sync path (CDC or outbox), so search results drift from the database.
Prefix vs leading wildcard on a B-tree. A B-tree can seek to a known prefix but has no starting point for a match in the middle of a string.
LIKE 'data%'LIKE '%data%'
Where matches sit in the indexOne contiguous rangeScattered everywhere
Plan with a B-treeIndex range scanSequential scan
Rows examinedOnly matching rangeEvery row
Right indexB-tree (text_pattern_ops)Trigram GIN or full-text

Code examples

Trigram index for substring search

CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX idx_jobs_title_trgm ON jobs USING gin (title gin_trgm_ops);

-- Now uses a Bitmap Index Scan on idx_jobs_title_trgm
EXPLAIN SELECT id, title FROM jobs WHERE title ILIKE '%backend%';

-- Typo-tolerant search ranked by similarity
SELECT title, similarity(title, 'bakend enginer') AS score
FROM jobs
WHERE title % 'bakend enginer'
ORDER BY score DESC
LIMIT 10;

The GIN trigram index makes leading-wildcard LIKE and ILIKE indexable, and the % operator adds fuzzy matching for misspelled search terms.

Full-text search with a stored tsvector

ALTER TABLE jobs ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(description, '')), 'B')
  ) STORED;

CREATE INDEX idx_jobs_search ON jobs USING gin (search);

SELECT id, title, ts_rank(search, q) AS rank
FROM jobs, websearch_to_tsquery('english', 'react developer -intern') q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;

A generated tsvector column stays in sync automatically, title matches are weighted above description matches, and websearch_to_tsquery accepts Google-style input such as quoted phrases and minus to exclude.

Key points

  • B-trees are sorted by string prefix, so only prefix LIKE patterns can use them.
  • In PostgreSQL, prefix LIKE needs C collation or text_pattern_ops to use a B-tree.
  • pg_trgm GIN indexes make %substring% and ILIKE indexable and add fuzzy matching.
  • Full-text search uses an inverted index of stemmed words and supports ranking.
  • Move to Elasticsearch or OpenSearch when you need facets, synonyms and relevance tuning at scale.

Common follow-up questions

  • How does an inverted index work?
  • How would you implement search-as-you-type autocomplete?
  • How would you keep Elasticsearch in sync with your primary database?
  • What is the difference between GIN and GiST indexes for text search?

Interview tips

  • Use the phone book analogy to explain why a leading wildcard defeats a sorted index; it lands instantly.
  • Distinguish substring search (trigrams) from word search (full-text); many candidates treat them as the same thing.
  • Show an EXPLAIN before and after to prove the index is used rather than claiming it.

Concepts covered

LIKE Wildcard, B-tree Index, Full-Text Search, pg_trgm, GIN Index

More Database Design questions