Key takeaways
- ✓An inverted index lists, for each word, the documents that contain it and how often. A search reads only its own words' lists, so it touches the documents that share a word with it, not the whole collection.
- ✓BM25 ranks with three rules. Rare words count more: "biomaterials", in 1 of 5,183 abstracts, weighs 8.15, and "the", in 5,159, weighs almost nothing. Each repeat adds less: one mention earns 3.7 of the 8.15, two 5.1, ten 7.3. And a match in a short document counts more than in a long one.
- ✓About 40 lines of Python BM25 tied OpenSearch on quality: nDCG@10 of 0.667 against 0.666, each uncertain by about ±0.02. Both put the same abstract first for 96.9% of the 1,109 claims.
- ✓Postgres's plainto_tsquery requires every word of the search in one document. On sentence-long searches, 1,024 of 1,109 (92%) came back empty. It did well on the 85 it answered (about 0.91), but empty answers score 0, so its quality overall was 0.070.
- ✓Matching any word fixed the empty answers but not the ranking: 0.588, clearly below BM25, because Postgres's ts_rank gives a common word the same weight as a rare one and by default ignores length. Measure search on your real queries before choosing an engine.
- ✓A search index is a copy of the database, and it lags. The sync worker took about 20 ms, but OpenSearch makes new documents searchable only at each refresh, once a second by default: a new row was found after 534 ms at the median and 1,072 ms at most. With a 100 ms refresh, 82 ms and 144 ms; the extra indexing work wasn't measured.
- ✓With the worker stopped for 10 s, search fell 11.0 s behind, then caught up, and nothing was lost: 400 rows, 400 documents. The worker reads changes without removing them and moves its bookmark only after OpenSearch has them, so a crash means resending, never losing. The price is that Postgres keeps its change log until the worker reads it.
Eleven hundred sentence-long searches against Postgres's built-in full-text search, set up to require every word: 1,024 came back with nothing. A search engine answered every one, and so did about 40 lines of Python, which ranked the answers just as well. This chapter takes apart what a search engine does that Postgres's default setup doesn't, measures the quality of each against human judgments, and then asks a second question: when a new row lands in the database, how long until search can find it?
The examples come from Lab 11 (Search, Geo and Object Storage) of the system design labs, scripts 01_search.py (three engines on the same searches) and 05_freshness.py (how long after a database write search finds it, and what happens when the sync worker stops), with the lab's modules inverted_index.py (the index and BM25, written from scratch), search_metrics.py (the quality score) and service/cdc.py (the worker that keeps the search index in step with Postgres). The same lab also covers typeahead, "drivers near me" search and large uploads (scripts 02 to 04); later chapters will cover those. The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): Postgres 17.7 and OpenSearch 2.19.7, one node, in Docker. The lab's 385 unit tests (BM25 against scores worked out by hand, the quality score, and the other scripts' modules) run in about 2 seconds without Docker; they all pass. Other work kept the laptop busy (a load average, the number of processes wanting a core, of about 5 to 17), so read the shapes, not the last digit.
The test: real abstracts, real judgments
The data is SciFact, a public research dataset: 5,183 scientific abstracts and 1,109 scientific claims, such as "0-dimensional biomaterials lack inductive properties." Each claim is used as a search. For every claim, people marked which abstracts are relevant (usually one, sometimes up to five), so each engine's answers can be scored.
Three ways to search the same text:
- Ours: an inverted index with BM25 ranking, written from scratch in Python (
inverted_index.py). - OpenSearch: an open-source search engine (a fork of Elasticsearch, built on the Lucene library), with its default settings and a
matchquery, which looks for any word of the search. - Postgres full-text search: a column of searchable words per abstract (
to_tsvector('english', …), which reduces words to their stems, so "properties" matches "property", and drops little words like "the", called stopwords), with a GIN index (Postgres's index type for "which rows contain this word") on it. Two ways of matching, both below.
The index at the back of a book
Think of the index at the back of a book: each word, then the pages it's on. A search looks up each of its words there, and ranking decides which pages to read first.
That's an inverted index. For each word, it keeps the list of documents that contain it and how many times, called the word's postings. A search reads only the lists for its own words, so its cost depends on how many documents share a word with it, not on the size of the collection. Ours holds 35,948 different words and builds in 0.3 s.
The first claim in the set has six words, once "0-dimensional" is split in two (the lab's tokenizer, like OpenSearch's default one, splits on anything that isn't a letter or a digit). Here is how many of the 5,183 abstracts contain each:
| Word | Abstracts containing it | BM25 weight |
|---|---|---|
| 0 | 951 | 1.70 |
| dimensional | 72 | 4.27 |
| biomaterials | 1 | 8.15 |
| lack | 168 | 3.43 |
| inductive | 2 | 7.64 |
| properties | 211 | 3.20 |
| the (for comparison) | 5,159 | 0.005 |
Rare words count more. "Biomaterials" is in one abstract, so finding it tells you almost exactly which abstract you want. "The" is in nearly all of them, so it tells you nothing. The weight is called idf (inverse document frequency):
idf = ln(1 + (N − df + 0.5) ÷ (df + 0.5)) N: all documents, df: documents with the word
biomaterials: ln(1 + (5,183 − 1 + 0.5) ÷ (1 + 0.5)) = ln(3,456) ≈ 8.15
One claim, used as a search: “0-dimensional biomaterials lack inductive properties.”
Like a book's index, the inverted index lists each word and where it appears. Pick a word: the fewer abstracts hold it, the more it says about which one you want.
* Not in the claim; shown for comparison. Counts on a log scale, from 1 abstract to all 5,183. “0-dimensional” splits into “0” and “dimensional”: the lab's tokenizer, like OpenSearch's default one, splits on anything that isn't a letter or a digit.
Rules two and three: what one abstract earns from “biomaterials”
Each repeat adds less, and the score never passes the weight. In an abstract of average length (225 words), one mention of “biomaterials” earns 3.70, two earn 5.09 and ten earn 7.27, of a possible 8.15. The same single mention earns 4.66 in an abstract half as long and 2.63 in one twice as long: a match in a short text counts more.
Counts recomputed from the pinned SciFact download with the lab's inverted_index.py; the scores use its BM25 with Lucene's defaults (k1 = 1.2, b = 0.75). An abstract's score for a search is the sum of these amounts over the search's words. The dotted curves are the other two lengths.
BM25 in three lines
BM25 is the ranking formula most search engines use by default, Lucene included. The lab's version uses Lucene's formula and default settings. The whole index is about 40 lines of code (60 with its comments), and three lines do the ranking, in inverted_index.py:
def idf(self, term: str) -> float:
df = len(self.postings.get(term, ()))
return math.log(1 + (self.n_docs - df + 0.5) / (df + 0.5)) # rule 1: rare words count more
# in scores(), for each word of the search and each document containing it:
norm = self.k1 * (1 - self.b + self.b * self.length[doc] / avg) # rule 3: length vs the average
out[doc] += idf * tf / (tf + norm) # rule 2: repeats add less
tf (term frequency) is how many times the word appears in the document. A document's score for a search is the sum over the search's words.
Repeats add less. tf ÷ (tf + norm) grows with each mention but never reaches 1, so a document can never earn more than the word's weight from it. In an abstract of average length (225 words), one mention of "biomaterials" earns 3.7 of its 8.15, two earn 5.1, ten earn 7.3. How fast it levels off is set by k1 (1.2, Lucene's default).
Short documents count more. The same single mention earns 4.66 in an abstract half the average length and 2.63 in one twice as long: one mention among 113 words says more than one among 451. How much length matters is set by b (0.75).
Ours vs OpenSearch
How good is each? The quality score is nDCG@10 (normalized discounted cumulative gain over the top 10). Each relevant abstract in the top 10 earns credit, less the further down it is (1 at rank 1, 1 ÷ log₂(r + 1) at rank r), and the total is divided by the best possible order's, so the score runs from 0 to 1, where 1 means the perfect order. The score for an engine is the average over all 1,109 claims, and an empty answer scores 0. The range in brackets is a 95% bootstrap interval: the claims resampled 2,000 times, which gives the range the true average probably lies in.
| Engine | Quality (nDCG@10) | Came back empty | Same top hit as OpenSearch | Top 10 in OpenSearch's top 10 | p50 | p99 |
|---|---|---|---|---|---|---|
| ours (BM25 from scratch) | 0.667 (0.644–0.690) | 0 | 96.9% | 96.6% | 2.71 ms | 6.78 ms |
| OpenSearch | 0.666 (0.643–0.688) | 0 | 2.52 ms | 8.81 ms | ||
| Postgres, every word | 0.070 (0.055–0.086) | 1,024 | 91.8% of 85 | 99.4% of 85 | 0.33 ms | 0.85 ms |
| Postgres, any word | 0.588 (0.564–0.614) | 0 | 57.1% | 45.0% | 5.15 ms | 11.62 ms |
It's a tie. 0.667 against 0.666 is a difference of one thousandth, and each score is uncertain by about two hundredths either way. Both put the same abstract first for 96.9% of the claims, and 72.9% of the claims got exactly the same ten.
The lab's README traces the rest, using OpenSearch's _explain API (which shows how a score was computed; its output isn't in the saved results). Lucene stores each document's length approximately, in one byte, so a 286-word abstract was scored as 280. Its tokenizer splits about 1% of the text differently (an average of 222.9 words per abstract against our 225.3). And its scores are 2.2 times ours, a constant factor of k1 + 1, which changes no order.
Postgres, every word
The lab's first Postgres search uses plainto_tsquery, Postgres's function for turning plain text into a search, and ranks with ts_rank, its ranking function, in 01_search.py:
SELECT id FROM docs, plainto_tsquery('english', $1) q WHERE tsv @@ q
ORDER BY ts_rank(tsv, q) DESC, id LIMIT 10
plainto_tsquery turns the sentence into "this word and this word and this word". It drops the stopwords and still requires all the rest, typically nine or so words per claim, in one abstract. For the first claim, the one abstract with "biomaterials" doesn't have the rest. For 1,024 of the 1,109 claims, no abstract had them all: 92% came back empty.
On the 85 it did answer, it was good: what it returned was almost always in OpenSearch's top 10 (99.4%). Its quality on those 85 works out to about 0.91. But an empty answer scores 0, and 1,024 zeros pull the average down to 0.070. It was also the fastest engine, because it returned so little.
Each square is one claim: 85 answered, 1,024 came back empty
Quality score (nDCG@10), with its 95% range
plainto_tsquery requires every word of the claim (after dropping little words like “the”) in one abstract. For 1,024 claims (92%) no abstract had them all. On the 85 it answered it did well, about 0.91 on average, and agreed with OpenSearch (99.4% of its results were in OpenSearch's top 10). But an empty answer scores 0: 85 × 0.91 ÷ 1,109 = 0.070. It was also the fastest, because it returned so little.
Recorded run, one per engine. nDCG@10 scores each top 10 against the abstracts people marked relevant (1 = the perfect order); the range is a bootstrap 95% interval over the 1,109 claims. The top-hit and overlap figures are over the claims the engine answered: 85 for Postgres with every word.
Postgres, any word
The fix the lab used: join the words with |, which means "or" in Postgres's search syntax, and pass that to to_tsquery:
def or_query(q: str) -> str:
words = [w for w in tokenize(q) if re.fullmatch(r"[a-z0-9]+", w)]
return " | ".join(words) if words else "nothing"
Now every claim had results, and quality rose to 0.588. Still clearly below BM25: the ranges don't overlap. Matching decides which abstracts are candidates; ranking decides their order, and that's where it lost. ts_rank ranks by how often the search's words appear, with no weight for how rare they are, so "lack" counts as much as "biomaterials" (stemming and stopwords only partly make up for it). By default it also ignores the document's length. Only 57.1% of its top hits matched OpenSearch's.
If your product search runs on Postgres and users type sentences, the lab's README suggests what to try before reaching for a separate engine: "or" the words, rank with a weight on rare words (an extension that adds BM25 to Postgres, for example), and measure nDCG on your real queries before and after. Postgres's websearch_to_tsquery, which the README and its answers also mention, accepts user syntax such as quotes and or, but still requires every unquoted word, so on its own it wouldn't fix sentence searches. Postgres's search still has real strengths, which the lab's checklist answers point out: short keyword searches, filters combined with SQL, and results that are up to date the moment a row is committed, because there's no copy to keep in step.
How long until search sees a new row?
That last point is the second half of the chapter. OpenSearch's index is a copy of the database, and a copy lags. Three ways to keep it updated, from the lab's README:
| Way | How | What goes wrong |
|---|---|---|
| Dual writes | The app writes the database, then the index | A crash between the two leaves them different, and nothing records it |
| Change data capture (CDC) | A worker reads the database's own change log and applies it | Lags by the worker's delay; a change can be applied twice |
| Periodic rebuild | Reindex everything every N minutes | Stale for up to N minutes |
The lab uses CDC. Postgres writes every change to its WAL (write-ahead log, from Chapter 7). A logical replication slot turns that log into a list of row changes and remembers how far its reader has got, like a bookmark. The lab's worker, service/cdc.py, reads new changes from the slot (it sleeps 20 ms when there are none), reads the changed rows, and sends them to OpenSearch in one bulk request.
The probe, 05_freshness.py, inserts 10 rows a second into Postgres, each with a unique made-up word, and checks OpenSearch every 10 ms two ways: fetch by id (has the worker delivered it?) and search for its word (can a search find it?). 200 rows per setting:
| OpenSearch's refresh interval | Visible as | p50 | p99 | Max |
|---|---|---|---|---|
| 1 s (the default) | fetch by id (the worker's part) | 18 ms | 37 ms | 43 ms |
| 1 s (the default) | found by search | 534 ms | 1,022 ms | 1,072 ms |
| 100 ms | fetch by id (the worker's part) | 23 ms | 40 ms | 47 ms |
| 100 ms | found by search | 82 ms | 143 ms | 144 ms |
The worker's part was about 20 ms. The rest was the refresh. OpenSearch doesn't make each new document searchable at once: it collects them and makes them searchable in batches, at each refresh, once a second by default (the index's refresh_interval setting). In the book picture, the index at the back is reprinted once a second, and a new page waits for the next printing. A row lands at a random moment between refreshes, so it waits half a second on average and at most about a second: 534 ms at the median, 1,072 ms at the slowest.
A 100 ms refresh cut it to 82 ms at the median. The cost is more indexing work: each refresh writes a new small piece of the index (a segment), and many small segments have to be merged in the background. This test didn't measure that cost, so measure it at your write rate before you change the setting. For the few writes that must be searchable at once, the lab's checklist answers suggest asking for it on that one request (OpenSearch's refresh=wait_for) instead of refreshing often for everything.
Recorded: 200 writes. “Fetchable by id” means the worker has handed the row to OpenSearch; “found by search” means a search for its unique word returns it.
Modelled: the index is reprinted every 1,000 ms, and a new row waits for the next reprint
Across: when the row is written, after the last refresh (one reprint to the next)
In the model, the worker hands the row over after 18 ms (the recorded median), and the row becomes searchable at the next refresh: this one is found after 700 ms. A row lands at a random moment, so the model's average is 18 + 500 = 518 ms and its worst 1,018 ms. The run measured 534 ms at the median and 1,072 ms at most.
When the worker stops
What if the worker stops? The probe stopped it at 10 s, for 10 s, while the 10 writes a second went on: 400 rows in 40 s.
worst write-to-search wait, per 5 s of writes (s): 1.0, 1.0, 11.0, 7.4, 2.5, 1.0, 1.0, 1.0
Search fell 11.0 s behind, then caught up. The worst row, written while the worker was stopped, waited 11.0 s: the 10 s stop plus, roughly, the restart and a refresh. Rows written later had less of the outage left to wait out, and rows written from 25 s on waited about a second again, as before. And nothing was lost: 400 rows in Postgres, 400 documents in OpenSearch.
Why nothing was lost is in the order of the worker's steps, shortened from service/cdc.py:
changes = await db.fetch("SELECT lsn::text, data FROM pg_logical_slot_peek_changes($1, NULL, 5000)", SLOT)
... # 1. peek: read, don't remove
r = await http.post("/_bulk", content="\n".join(lines) + "\n", ...) # 2. send to OpenSearch, each by its id
...
await db.execute("SELECT pg_replication_slot_advance($1, $2::text::pg_lsn)", SLOT, changes[-1]["lsn"])
# 3. only then move the bookmark
The worker peeks (reads changes without removing them), sends, and only after OpenSearch has accepted them moves the bookmark (the slot's position, an lsn, a position in the log). A crash anywhere before step 3 means the same changes are sent again on restart, instead of lost. Sending one twice is harmless: a document with the same id just overwrites itself. That's at-least-once delivery, made safe because applying a change twice gives the same result, the same idea as the idempotent retries of Chapter 10.
The price goes to the database. Postgres keeps the change log until the slot's reader moves the bookmark. A worker that stays down long enough fills the database's disk, unless you cap how much log a slot may hold (Postgres's max_slot_wal_keep_size setting; past it, Postgres gives up on the slot instead, so the worker can't resume and the index has to be rebuilt). The lab didn't test that.
Caveats
- One run per row, on a busy laptop. The quality scores are averages over 1,109 claims, with the intervals shown; the latencies and freshness numbers are single runs. With 200 writes, a p99 is close to the slowest few rows.
- One dataset. SciFact's searches are whole sentences, which is the worst case for every-word matching. On short keyword searches, Postgres's default would come back empty far less often. Measure on your own queries.
- Words aren't meaning. For the first claim, the one abstract the judges marked relevant isn't in either BM25 top 10. Keyword ranking can't find a match that uses different words; that's what synonyms, stemming and learned ranking on top are for. Our index does no stemming at all, and neither does OpenSearch's default analyzer.
- The
_explainfindings (one-byte lengths, 1% different tokenizing, the 2.2× factor) are from the lab's README; their output wasn't saved with the results. - The worker-down run stopped the worker once. The crash cases in the third widget are illustrations of the code's step order, not runs. The disk-filling risk and the cost of faster refreshes weren't measured.
- A copy keeps its own state. The lab's README records that the freshness probe's deleted rows stayed in OpenSearch's statistics until its index pieces were merged, which changed BM25's document count from 5,183 to 6,783 and with it the search scores. The search numbers above were recorded before the probe ran, and the probe now merges after cleaning up.
- Not covered here: Lab 11's typeahead, geo search and upload scripts, which later chapters will cover.
The checklist
- Test search on real queries, scored against relevance judgments (nDCG@10), and count the empty answers: an engine that answers nothing for 92% of searches can look fine on the rest.
- Know how your search matches: every word or any word. Sentence-long searches need any-word matching.
- Rank by rare words. BM25's idf is what separates "biomaterials" from "the"; a ranking without it (Postgres's
ts_rank) scored 0.588 against 0.667. - Treat the search index as a copy that lags. Measure write-to-search time end to end: here it was set by the refresh interval, not the sync worker.
- Keep it in step with change data capture, not dual writes. Read the change log, apply by id, and move the bookmark only after the index has the changes.
- Watch the worker, and cap how much log the database keeps for it. A stopped worker means stale search; one stopped for too long means a full disk.
Practice: rank by rare words, and keep the copy in step
Write the lab's logic: the tokenizer and inverted index, BM25's weight and score, a search that ranks by it, Postgres-style every-word matching, nDCG@10 with empty answers scoring 0, the refresh model behind the third widget, and one pass of the sync worker, which must lose nothing when it crashes before moving its bookmark. The tests include the lab's own BM25 tests and the recorded numbers: weights of 8.15 and 3.2, 3.7 / 5.1 / 7.3 for one, two and ten mentions, and 0.07 overall against about 0.91 on the 85 claims answered.
Quiz
1.In the abstracts, "biomaterials" appears in 1 abstract and "the" in 5,159. How does BM25 weigh them?
2.An abstract of average length mentions "biomaterials" once, and it earns 3.7 of its 8.15. What do ten mentions earn?
3.Ours scored 0.667 and OpenSearch 0.666, each uncertain by about ±0.02. What's the right reading?
4.Why did Postgres with plainto_tsquery return nothing for 1,024 of 1,109 claims?
5.Joining the words with "or" gave every claim results. Why was quality still 0.588, below BM25's 0.667?
6.The sync worker hands a new row to OpenSearch in about 20 ms, but a search found it after 534 ms at the median. Where did the rest go?
7.The worker was stopped for 10 s while writes went on. Why was nothing lost?
Check your understanding
Try each question before opening its answer.
What is an inverted index, and why is a search with it fast?
For each word, it lists the documents that contain it and how often. A search looks up only its own words' lists, so it touches only the documents that share a word with it, not the whole collection. Ours held 35,948 words for 5,183 abstracts and built in 0.3 s.
What does each of BM25's three rules do, with the numbers from the first claim?
Rare words count more: "biomaterials", in 1 abstract, weighs 8.15, "properties", in 211, weighs 3.2, and "the", in 5,159, almost nothing. Repeats add less: at average length, one mention earns 3.7 of the 8.15, two 5.1, ten 7.3. Short documents count more: one mention earns 4.66 in an abstract half the average length and 2.63 in one twice as long.
Our 40 lines scored 0.667 and OpenSearch 0.666. Why call it a tie, and why weren't they identical?
Each score is uncertain by about ±0.02 (0.644–0.690 and 0.643–0.688), far more than the difference. They use the same formula; the lab's README traces the rest to details: OpenSearch stores document lengths approximately, its tokenizer splits about 1% of the text differently, and its scores carry a constant factor that changes no order. Both put the same abstract first for 96.9% of the claims.
Postgres answered only 85 claims with every word required, and did well on those. Why was its overall quality 0.070?
An empty answer scores 0, and the average is over all 1,109 claims: about 0.91 × 85 ÷ 1,109 ≈ 0.07. Sentence-long searches still have nine or so words after stopwords are dropped, and for 1,024 claims no abstract had them all.
Joining the words with "or" gave every claim results. What was still wrong?
The ranking. Postgres's ts_rank counts how often the words appear but gives a common word the same weight as a rare one, and by default ignores length. Quality was 0.588 against BM25's 0.667, with ranges that don't overlap, and only 57.1% of its top hits matched OpenSearch's.
The sync worker delivers a new row in about 20 ms. Why did search find it only after about half a second?
OpenSearch makes new documents searchable only at each refresh, once a second by default. A row lands at a random moment between refreshes, so it waits about half the interval on average and at most a whole one: 534 ms at the median, 1,072 ms at most. A 100 ms refresh gave 82 ms, at the cost of more indexing work, which wasn't measured.
The worker could crash after sending changes to OpenSearch but before moving its bookmark. What happens, and why is that acceptable?
On restart it reads the same changes again from Postgres and sends them again. That's harmless because each document is written under its row's id, so a second copy overwrites the first. Moving the bookmark only after OpenSearch has the changes means a crash causes a resend, never a loss: with the worker stopped for 10 s, all 400 rows arrived, the worst after 11.0 s.
What does a stopped sync worker cost the database, and how do you limit it?
Postgres keeps every change in its log until the slot's reader moves the bookmark, so the log grows for as long as the worker is down, and a long outage can fill the disk. Monitor the worker's lag and cap how much log a slot may keep; past the cap Postgres gives up on the slot, and the index has to be rebuilt. The lab didn't test this.
Next up: typeahead and nearby search, coming soon. The same lab's next scripts answer "the top 10 completions of what I've typed" on every keystroke, and "every driver within 2 km": two more kinds of index that aren't a table with a B-tree.