Search Systems
How a full-text search index works, how text is analysed and ranked, how it is sharded and synced with the database, and what interviewers ask.
On this page
A search system finds the documents that match the words in a query and puts the best matches first. It is built on an inverted index, a data structure that maps each word to the list of documents containing it, so a query looks up a few lists instead of reading every document. The index is a copy of data that lives in a database.
Without an inverted index, search is usually written as WHERE title LIKE '%red shoes%'. A pattern that starts with % cannot use an ordinary database index, so every query reads every row. It also misses "Red Shoe" and can neither rank matches nor tolerate typos.
Where search sits in a system
request and replyasynchronous message
The index answers "which documents match this text, in what order" and returns document ids. Values that must be correct, such as prices and stock, are read from the database afterwards.
The inverted index
An inverted index maps each token (a normalised word) to a sorted list of the ids of the documents that contain it. That list is the postings list of the token. The table shows four titles after analysis, which the next section describes.
| Document | Title | Tokens |
|---|---|---|
| 1 | Red Running Shoes | red, run, shoe |
| 2 | Blue running shorts | blue, run, short |
| 3 | Red leather shoe | red, leather, shoe |
| 4 | Red rain jacket | red, rain, jacket |
The index for these documents contains red → [1, 3, 4], shoe → [1, 3] and run → [1, 2], plus a one-document list for each remaining token. To answer a query, the engine analyses the query in the same way, fetches the postings list of each token, and combines the lists. For a query where every word must match, it intersects the lists by walking through them together.
- query0Red1shoestokens0red1shoe
1The same analysis turns the query into the tokens
redandshoe. - red011324shoe0113
2The engine fetches the sorted postings list of each token.
- red01i1324shoe01j13
- matches
- [1]
3Both pointers are at document 1, so document 1 contains both words. Both pointers move forward.
- red0113i24shoe0113j
- matches
- [1, 3]
4Both pointers are at document 3, which is another match. Both pointers move forward.
- red011324ishoe0113j
- matches
- [1, 3]
- comparisons
- 2
5The shoe list has ended, so no later document can contain both words. Document 4 is never examined.
This walk is the two-pointer technique on sorted lists. Its cost depends on how many documents contain each word, not on the total number of documents. The token dictionary is kept sorted or in a trie, which also allows prefix queries such as "sho".
Positions and segments
A postings list can also store the position of the word in each document, which is what makes phrase queries such as "red running shoes" possible: the engine checks that the words appear next to each other. In practice the index is written as immutable segments. New documents go into a small new segment that becomes searchable after a refresh, normally about a second later, and a delete only marks the document as removed. Background merges combine small segments into larger ones and drop the deleted documents.
Text analysis
Analysis is the pipeline that turns raw text into tokens. It runs once when a document is indexed and again, with the same settings, on every query. If the two differ, the query tokens do not match the indexed tokens, and a search for "shoes" finds nothing in an index that stores the stem "shoe".
Tokenising
Tokenising splits the text into words, usually at spaces and punctuation. The details matter: whether "e-mail" is one token or two, how a model number such as "RTX-4090" is split, and how languages without spaces are cut into words.
Lowercasing
Every token is converted to lower case, so "Red" and "red" are the same token.
Stemming
Stemming reduces a word to a root by stripping its ending, so "running" and "runs" become "run" and "shoes" becomes "shoe". It is rule-based, so it makes mistakes: an aggressive stemmer can reduce "university" and "universe" to the same stem.
Stop words
Stop words are very common words, such as "the" and "of", that are dropped from the index to save space. Removing them has a cost: the title "To Be or Not To Be" becomes empty, and a phrase search for "the who" cannot be answered. Modern engines usually keep them, because ranking already gives common words a low weight.
Ranking
Matching decides which documents are candidates, and ranking decides their order. The standard text score has two parts. Term frequency (TF) rewards a document in which the query word appears many times. Inverse document frequency (IDF) weights each query word by how rare it is across all documents, so a match on "waterproof" counts for more than a match on "black" when "waterproof" is in far fewer documents.
BM25 is the formula most search engines use by default, and it refines TF-IDF in two ways. The benefit of repeated occurrences levels off, so a document that mentions a word 50 times does not score 50 times higher than one that mentions it five times. The score is also adjusted for document length, so a match in a short title counts for more than the same match in a long description. Products also combine this score with popularity and recency.
Sharding and replicating the index
When the index is too large for one machine, or one machine cannot serve the query rate, it is split into shards, and each shard is copied to replicas.
Sharding by document
Each shard holds a complete inverted index for its own subset of the documents, chosen by hashing the document id. A query is sent to every shard. Each shard returns its own top results, and the coordinator merges them into one ordered list. A document is written to exactly one shard, so an update is cheap, and the load is spread evenly.
The weakness is that every query touches every shard, so the slowest shard decides the response time, and adding shards does not make a single query cheaper. Each shard also computes IDF from its own documents, so scores differ slightly between shards.
Sharding by term
With term sharding, each word's complete postings list lives on one shard, so a query goes only to the shards that own its words. It works poorly in practice. Indexing one document touches the shard of every word in it, a common word such as "red" has a very long list on one shard that becomes a hot spot, and a multi-word query must ship long lists across the network. For these reasons document sharding is the standard choice.
Replicas
Each shard is stored on several nodes. Replicas keep search available when a node fails and add query capacity, because any copy of a shard can answer a query. Add replicas for more query capacity and shards for more data. Replicas are updated by the indexing process, so they can be briefly behind each other. See replication and sharding and partitioning.
Keeping the index in step with the database
The database is the source of truth, so every change to it must reach the index. There are three ways to do this.
Dual write from the application
The application writes the database and then writes the search index in the same request. If the process crashes or the index call fails between the two writes, the two disagree, and nothing detects or repairs it. Concurrent updates can also reach the index in the opposite order to their commits, leaving the older version. This is acceptable for a prototype and not for production.
Change stream
The application writes only the database. A change data capture process reads the database's commit log and publishes each committed change to a stream, and an indexer consumes the stream and updates the index. Because the stream is ordered and retained, the indexer can resume after a crash without losing a committed change. Each event carries the row's version, and the index ignores an event that is not newer than the version it holds, so replaying events cannot undo a later edit. See message queues and streams.
The cost of this design is lag. A change appears in search results a second or a few seconds after the commit, and later when the indexer falls behind.
Periodic rebuild
A batch job reads the whole table, builds a new index and swaps it in, for example every night. It is simple and always correct, because each rebuild removes any drift. Changes wait for the next rebuild, and rebuilding a large table is slow. Even when a change stream is used, a rebuild is kept as the recovery path and as the way to apply a new analyser.
Pagination, staleness, analyser changes and typos
Deep pagination
A request for page 1,000 with 10 results per page asks for results 9,991 to 10,000. No shard knows which of its documents fall in that range, so every shard must return its top 10,000 results and the coordinator merges all of them to keep ten. Engines usually refuse offsets beyond a limit such as 10,000. The fix is cursor-based pagination: the client sends the sort values and id of the last result it received, and each shard returns only the next ten after that position. It supports only "next" and not "jump to page 500", which real users rarely need.
Results that lag behind a write
A seller who edits a product and searches immediately may still see the old title, because the change is still moving through the stream. Search can accept that delay, while the seller's own edits and any value that must be exact are read from the database.
Changing the analyser
If the stemmer or tokeniser changes, the stored tokens no longer match what queries produce, so the index must be rebuilt: fill a new index from the table and then from the change stream, and switch queries to it in one step.
Typos
Typo tolerance uses fuzzy matching, which finds indexed words within an edit distance of one or two from the query word, or character n-grams, which let a misspelling share most of its fragments with the right word. Both enlarge the index, so they are limited to longer words and small distances.
Typeahead and location search
Autocomplete matches prefixes of popular queries within a few milliseconds, so it uses its own small prefix index and is covered in Design Typeahead Search. Searching for places near a point uses a geospatial index such as a geohash grid or a quadtree, covered in Design Proximity Search.
In the interview
Propose a search index when the requirement is free-text search, ranking, typo tolerance or filtering on many fields. Below a few million rows, the database's own full-text feature is often enough. State what is indexed, how the index is fed, how stale it may be, and which values are always read from the database.
- "Why not use LIKE in the database?" A pattern that starts with a wildcard cannot use an ordinary index, so each query scans every row, and there is no ranking, stemming or typo tolerance. An inverted index reads one list per word and touches only matching documents.
- "How does the index stay in sync with the database?" The application writes only the database, and change data capture feeds an indexer through a stream. The indexer can replay after a crash, and versions on events stop old events from overwriting newer data. A nightly rebuild repairs any drift.
- "How do you shard the index?" By document, so each shard holds a complete index of a slice of the documents. Queries go to all shards and the top results are merged. Term sharding makes writes touch many shards and creates hot lists.
- "How do you paginate deep results?" Offset pagination makes every shard return all results up to the offset, so it slows with each page. Use a cursor made of the last result's sort values and id, which keeps the cost constant but allows only moving forward.
Users need to search 20 million products by text. Can't the database do it?
With ranking and typo tolerance required, I'd add a search index. The product service writes only to the database, and change data capture feeds the index through a stream, so the index is a second or two behind and can be rebuilt from the database at any time.
A seller changes a price. Does search show the new price?
Search returns product ids, and the service reads price and stock from the database or its cache. A stale index can show an old title for a few seconds, but it cannot show a wrong price.
Why is change data capture preferred over the application writing to the index itself?
A search index is split into shards by document id. A user asks for page 2,000 of the results. What is the main problem?
Of 1 million products, "waterproof" appears in 2,000 and "black" in 300,000. For the query "black waterproof", which word should weigh more in ranking?
What to practise next
Read Design Typeahead Search for prefix search and Design Proximity Search for location search. Message queues and streams and idempotency and retries cover the change stream and safe replay.