Skip to content

Lesson 21 of 38Running in production

Search and Inverted Indexes

Why LIKE queries fall over, how inverted indexes and BM25 work, how Elasticsearch and OpenSearch run them, and when Postgres or hybrid search is enough.

19 min read0/5 questions

The last three lessons kept a system healthy. This one closes the unit with a component almost every product adds once it is running: search. The shop has five million products and a search box. The first version was WHERE name ILIKE '%running shoes%'. It took four seconds at peak, missed "running shoe" and "shoes for running", and returned a sock above the shoes because the sock happened to come first. Search is one of the first features that outgrows the main database, and almost every product has it: products, tickets, logs, docs, messages. This lesson shows what a search engine actually builds, how it ranks, how Elasticsearch and OpenSearch spread that across a cluster, and how to keep the index in step with your database without losing writes.

Why LIKE cannot scale

A normal B-tree index is sorted by the column's value from the first character. That makes LIKE 'run%' fast, because the database can jump to "run" and read forward. A leading wildcard, LIKE '%run%', gives it nowhere to jump. It has to read every row and scan every string. Five million products times a 200-character description is a gigabyte of text per query, and it gets worse as the catalogue grows.

Even when it is fast enough, LIKE answers the wrong question:

  • No relevance. Rows match or they do not. There is no "best" result first.
  • No language. "running" does not match "run". "Shoe" does not match "shoes". Case and accents trip it up.
  • No multi-word logic. '%running shoes%' misses "shoes for running". Splitting the words gives you a pile of ORs and even slower scans.
  • No typos. "runnign" finds nothing.

(Postgres can index LIKE '%term%' with the pg_trgm extension, covered below. That fixes speed, not relevance.)

Search engines flip the problem around. Instead of scanning documents for a word, they look the word up and get the documents.

The inverted index

An inverted index maps each term to a posting list: the sorted IDs of the documents that contain it, often with the positions where it appears. It is the index at the back of a book, built for every word.

Building one starts with analysis, the pipeline that turns raw text into terms. The same analyser must run on documents at index time and on the query at search time. When the two differ (stemming on one side, not the other), searches silently miss, and it is one of the most common search bugs in production.

Analysing 'Running Shoes for the Trail'
  1. Running Shoes for the Trailraw text
  2. Running | Shoes | for | the | Trailtokenizer: split on word boundaries
  3. running | shoes | for | the | traillowercase filter
  4. running | shoes | trailstop-word filter (positions kept)
  5. run | shoe | trailstemmer

The tokenizer splits text into tokens and records each token's position: 0, 1, 2, 3, 4.

1/4

With terms in hand, queries become operations on sorted lists:

  • AND intersects posting lists. Because both lists are sorted, a two-pointer merge does it in one pass. Engines start from the shortest list, and skip lists let them jump ahead rather than step one ID at a time.
  • OR unions them.
  • Phrase queries ("road running") intersect the lists, then check that the positions are adjacent.

Run a tiny engine with all three.

Pythoninverted_index.py
import refrom collections import defaultdict docs = { 1: "Running shoes for trail running", 2: "The best road running shoes", 3: "Trail jacket, waterproof and light", 4: "Shoes for the road: a buyer's guide",} STOP = {"the", "for", "and", "a"} def analyze(text): tokens = re.findall(r"[a-z0-9']+", text.lower()) # tokenize + lowercase out = [] for pos, tok in enumerate(tokens): if tok in STOP: continue tok = re.sub(r"(ning|ing|s)$", "", tok) or tok # a toy stemmer out.append((tok, pos)) # keep the position return out index = defaultdict(lambda: defaultdict(list)) # term -> {doc_id: [positions]}for doc_id, text in docs.items(): for term, pos in analyze(text): index[term][doc_id].append(pos) for term in ["run", "shoe", "trail", "road"]: print(f"{term:>6} -> {dict(index[term])}") def postings(word): term = analyze(word)[0][0] # same analyzer at query time return sorted(index[term]) def AND(a, b): # two-pointer merge of sorted lists i = j = 0 out = [] while i < len(a) and j < len(b): if a[i] == b[j]: out.append(a[i]); i += 1; j += 1 elif a[i] < b[j]: i += 1 else: j += 1 return out def OR(a, b): return sorted(set(a) | set(b)) def phrase(first, second): t1, t2 = analyze(first)[0][0], analyze(second)[0][0] hits = [] for doc_id in AND(sorted(index[t1]), sorted(index[t2])): if any(p + 1 in index[t2][doc_id] for p in index[t1][doc_id]): hits.append(doc_id) return hits print("\nrunning AND shoes:", AND(postings("running"), postings("shoes")))print("trail OR road: ", OR(postings("trail"), postings("road")))print('"road running": ', phrase("road", "running"))print('"running road": ', phrase("running", "road"))
Output
Press Run (⌘ Enter) to see what happens.

Real engines compress posting lists heavily (delta-encode the sorted IDs, then pack the small gaps into a few bits each) and store the term dictionary in a compact automaton (Lucene uses a finite state transducer). That is how an index of billions of terms fits in memory-friendly structures.

Quick check
Documents are indexed with an English stemmer, but the query path uses a plain whitespace analyser. A user searches 'running'. What happens?
Need a nudge? A hint rules out a wrong answer.

Ranking: from TF-IDF to BM25

Matching is half the job. Ordering is what users notice. The classic intuition is TF-IDF:

  • Term frequency (TF): a document that mentions "kafka" five times is probably more about Kafka than one that mentions it once.
  • Inverse document frequency (IDF): a term that appears in almost every document ("the", "shoes" in a shoe shop) tells you little. Rare terms carry more weight.

Raw TF-IDF has two flaws. Repeating a word keeps raising the score forever, so keyword stuffing wins. And long documents match more terms just by being long. BM25 fixes both, and it is the default ranking in Lucene, Elasticsearch, and OpenSearch:

  • TF saturation. The score rises quickly for the first few mentions, then flattens. The parameter k1 (default 1.2) controls how fast.
  • Length normalisation. A match in a short title counts for more than the same match in a long page. The parameter b (default 0.75) controls how strongly length is penalised relative to the average document.

Run it. Document B repeats "kafka" six times and has the highest raw term count. Watch where it lands.

Pythonbm25.py
import mathfrom collections import Counter docs = { "A": "kafka consumer lag alert", "B": "kafka kafka kafka kafka kafka kafka tutorial", "C": "how to reduce consumer lag in kafka when partitions are hot and the consumer group keeps rebalancing", "D": "postgres replication lag",}tokens = {d: text.split() for d, text in docs.items()}N = len(docs)avgdl = sum(len(t) for t in tokens.values()) / Nk1, b = 1.2, 0.75 # Lucene's defaults def idf(term): n = sum(term in t for t in tokens.values()) # docs containing the term return math.log(1 + (N - n + 0.5) / (n + 0.5)) # Lucene's BM25 idf def bm25(query, doc): tf, dl = Counter(tokens[doc]), len(tokens[doc]) score = 0.0 for term in query.split(): f = tf[term] score += idf(term) * f * (k1 + 1) / (f + k1 * (1 - b + b * dl / avgdl)) return score def tf_only(query, doc): return sum(Counter(tokens[doc])[t] for t in query.split()) q = "kafka consumer lag"print("idf:", {t: round(idf(t), 2) for t in q.split()})print(f"\n{'doc':<4}{'raw tf':>7}{'bm25':>7}")for d in sorted(docs, key=lambda d: -bm25(q, d)): print(f"{d:<4}{tf_only(q, d):>7}{bm25(q, d):>7.2f}")
Output
Press Run (⌘ Enter) to see what happens.

The short document that matches all three terms wins. Saturation stops B's repetition from paying off, and length normalisation keeps C's many matches from beating A. In real products BM25 is the base layer, and teams add boosts on top: a match in the title outweighs one in the body, in-stock items rank higher, popular items get a nudge. Two facts seniors know: scores are only comparable within one query, never across queries, and in a sharded index each shard computes IDF from its own documents by default, so small indexes can rank inconsistently (Elasticsearch's dfs_query_then_fetch computes global statistics at extra cost).

How Elasticsearch and OpenSearch run it

Elasticsearch and OpenSearch (the Apache-licensed fork) are both built on Lucene and share the same core design.

  • An index is a logical collection of documents, split into primary shards. Each shard is a complete Lucene index. The primary count is fixed when the index is created; changing it means a split or shrink operation, or a reindex.
  • Each primary has replicas on other nodes, for failover and for spreading read load.
  • Inside a shard, data lives in immutable segments. New documents collect in a memory buffer; a refresh (every 1 second by default) writes them out as a new searchable segment. That is why search is near real time: a document you just indexed is not visible for up to a second. Durability comes separately from the translog, an append-only log that is replayed after a crash.
  • Because segments never change, an update is a delete plus a new document, and a delete only marks the old one. Background merges combine small segments and purge deleted documents, just like compaction in the LSM trees from How Databases Store Data.
A search request, scatter and gather
Search APISearch APICoordinating nodeCoordinating nodeShard 0: primary or replicaShard 0primary or replicaShard 1: primary or replicaShard 1primary or replicaShard 2: primary or replicaShard 2primary or replicaq=trail shoes, size 10

Any node can coordinate. It receives the query and knows which shards hold the index.

1/4

Sizing rules of thumb you will hear: keep shards in the tens of gigabytes, not hundreds, and avoid thousands of tiny shards, since each one costs memory and a slot in every scatter. Check the vendor's current guidance for exact numbers.

Quick check
A test indexes a product, immediately searches for it, and finds nothing. A second later the same search finds it. Why?
Need a nudge? A hint rules out a wrong answer.

Keeping search in sync with the database

The database stays the source of truth. The search index is a derived copy you can rebuild at any time. The hard part is keeping the copy current.

The tempting design is a dual write: save to Postgres, then index into Elasticsearch in the same request. It has the exact crash windows you saw in Sagas, Outbox, and Two-Phase Commit: a crash or a failed index call leaves the index silently stale, and concurrent updates can reach the index in the wrong order. The reliable designs:

  • CDC or outbox into an indexer. Debezium streams row changes, or the service writes outbox events, into Kafka. An indexer consumes them and writes to the search engine. Partition by document ID so updates to one product stay in order, and use the row's version or update timestamp with external versioning, so the engine rejects an older version that arrives late.
  • Re-read on event. The event only says "product 812 changed". The indexer fetches the current row and indexes that. Simpler, always fresh, and duplicates are harmless; the cost is a read per event.

Plan for full reindexes from day one. You will need them when you change an analyser, a field mapping, or the shard count, because existing segments cannot be changed in place. The zero-downtime recipe uses an alias, a stable name that points at a real index.

Put it in order6 steps

Order the steps of a zero-downtime reindex behind an alias.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Postgres full-text search: the good-enough first step

Before running a search cluster, check whether Postgres is enough. For a catalogue in the low millions with modest query volume, it often is, and you avoid a second system to sync. Full-Text Search in the Database in the SQL & Databases course covers the queries and ranking in depth; here is the shape of it.

migrations/0051_product_search.sql
-- A stored generated column keeps the document vector in sync automatically.
ALTER TABLE products ADD COLUMN search tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(description, '')), 'B')
  ) STORED;
 
CREATE INDEX products_search_idx ON products USING GIN (search);
 
-- websearch_to_tsquery accepts what users type: quotes, OR, and -exclusions.
SELECT id, name, ts_rank(search, q) AS rank
FROM products, websearch_to_tsquery('english', 'trail "running shoes" -kids') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;
 
-- Fuzzy matching and fast substring search with trigrams.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX products_name_trgm ON products USING GIN (name gin_trgm_ops);
SELECT name FROM products WHERE name % 'runnign shoes' ORDER BY similarity(name, 'runnign shoes') DESC LIMIT 5;

A tsvector is Postgres's own analysed, positional term list, and a GIN index is an inverted index over it. The weights let a title match outrank a description match. The pg_trgm extension splits strings into three-letter chunks, which gives typo-tolerant similarity search and lets a GIN index speed up LIKE '%term%'.

The limits: ts_rank is not BM25 and has no corpus-wide IDF, so relevance is cruder; facets, synonyms, per-language analysers, and autocomplete need more work; and heavy search load competes with your transactional queries on the same primary. Move to a dedicated engine when relevance tuning becomes a product feature or search load starts to hurt writes. Extensions that add BM25 ranking to Postgres exist too; evaluate them against your hosting provider's supported list.

Keyword search matches words. It fails on meaning: "shoes for jogging on mud" shares few terms with "waterproof trail runner". Vector search embeds documents and queries as vectors with a model, then finds the nearest vectors using an approximate nearest-neighbour index such as HNSW. The AI Engineering course's lesson on RAG and embeddings covers how embeddings are made.

Vectors have the opposite weakness. They are fuzzy on exact tokens: product codes, error messages like ERR_CONN_RESET, names, and version numbers. So production search increasingly runs hybrid search: a BM25 query and a vector query in parallel, then a merge. The scores are on different scales and cannot be added, so the standard merge is reciprocal rank fusion (RRF), which only uses each document's rank in each list: score = sum of 1 / (k + rank), with k usually 60. A document that ranks well in both lists rises to the top.

Pythonrrf.py
keyword = ["doc-7", "doc-2", "doc-9", "doc-4"] # BM25 ordervector = ["doc-2", "doc-5", "doc-7", "doc-1"] # embedding similarity order def rrf(*rankings, k=60): scores = {} for ranking in rankings: for rank, doc in enumerate(ranking, start=1): scores[doc] = scores.get(doc, 0) + 1 / (k + rank) return sorted(scores.items(), key=lambda kv: -kv[1]) for doc, score in rrf(keyword, vector): print(f"{doc} {score:.4f}")
Output
Press Run (⌘ Enter) to see what happens.

Elasticsearch, OpenSearch, and Postgres with pgvector all support some form of hybrid query today; the APIs differ and move quickly, so check the current docs. A re-ranker model on the top 50 results is the usual next step when relevance really matters.

Predict the outputPython

doc-7 is rank 1 in the keyword list and rank 3 in the vector list. doc-2 is rank 2 and rank 1. With k = 60, which comes first?

k = 60
doc7 = 1/(k+1) + 1/(k+3)
doc2 = 1/(k+2) + 1/(k+1)
print("doc-2" if doc2 > doc7 else "doc-7")
Need a nudge? Hints walk you through it.

Typos, facets, and autocomplete

Three features users expect, and how engines build them:

  • Typo tolerance. Fuzzy queries match terms within a small edit distance. Elasticsearch's fuzziness: AUTO allows no edits for very short terms, one for medium ones, and two for longer ones, because "cat" to "car" is a different word while "runnign" to "running" is a typo. Fuzzy queries are slower, so many sites run them only when the exact query returns few results.
  • Facets. The counts beside "Brand: Nike (213)" come from aggregations over keyword fields, computed on the matching documents in the same request. They read column-oriented doc values, not the inverted index.
  • Autocomplete. Suggestions as you type are a different problem with tighter latency limits. Search Autocomplete covers it in full: prefix tries, edge n-grams, and ranking by popularity.
Match the pairs0/5 matched

Match each requirement to the right tool.

Choose an item, then its match on the other side.
Key terms
inverted index
A map from each term to the sorted list of documents (and positions) containing it.
posting list
The sorted document IDs, and often positions, stored for one term in an inverted index.
analyser
The pipeline of tokenizer and filters (lowercase, stop words, stemming) that turns text into index terms. Must match at index and query time.
BM25
The default relevance formula in Lucene-based engines: TF-IDF with term-frequency saturation and document-length normalisation.
segment
An immutable chunk of a Lucene index. Refresh creates new ones; merges combine them and purge deletes.
near real time
New documents become searchable after the next refresh, about a second by default, rather than instantly.
reciprocal rank fusion
Merging ranked lists by summing 1 / (k + rank) per document, used to combine keyword and vector results.