Stage 2 · Building blocks · Medium · 18 min
Search indexes and autocomplete
See how a search engine finds text without reading every row: an inverted index for whole words, and a trie for suggestions as you type.
What each interview level is expected to know
Learn first: Indexes and storage engines
In AI systems: AI basics, in plain English, Retrieval and vector search in depth
After this lesson you can:
- Build an inverted index and explain how it finds words without reading every row.
- Use a trie for suggestions as the user types, with top results kept at each node.
- Keep the index in step with the database, and suggestions fresh.
Start here
See it in 60 seconds
How autocomplete finds suggestions
Autocomplete walks a tree of letters, called a trie, to find the most popular queries that start with what you typed.
Scene 1 of 6 · What people typed
A search box has seen 7 queries, each with how often people typed it.
| Query | Times typed |
|---|---|
| card | 90 |
| car | 70 |
| dog | 60 |
| care | 40 |
| door | 30 |
| cat | 25 |
| cap | 10 |
- Steps taken, one per letter
- 0
- Queries stored
- 7
- What people typed. A search box has seen 7 queries, each with how often people typed it.
- One letter per node. A trie stores them letter by letter, so queries that start the same share a path.
- Type c. Typing c takes one step down, and everything below that node starts with c.
- Then a. After c and a, the node already knows its top three: card, car and care.
- Some queries end early. car is a full query, yet its path goes on to card and care.
- Speed depends on letters. Each letter is one step, so the work depends on how much you type, not on how many queries exist.
- Now you try. Tap letters to type the start of a query, and see what the trie suggests. For example, tapping c and a gives this: "ca" takes 2 steps and suggests card (90), car (70) and care (40). The suggestions are the most typed queries below this node, most popular first.
Scene 1 of 6: What people typed. A search box has seen 7 queries, each with how often people typed it.
Key points
- A trie stores text one letter per node, so queries that start the same share one path.
- Typing walks one node per letter, then reads the suggestions kept at that node.
- The work grows with the letters typed, not with the number of queries stored.
- Real search boxes also rank results, fix typos and update counts as people search.
In plain words
Say a search box has seen seven queries, and card is the most typed, at 90 times. A user types c, then a. The box should offer card, car and care right away, without checking all seven. A (A tree that stores words one letter per step, so words that start the same share a path.) makes that possible. It is a tree that adds one letter at each level, so everything beginning with ca hangs under a single (In a tree, such as a trie: one point that holds a value and links to the points below it.). Searching for whole words inside documents uses another structure, the inverted (An extra structure, kept sorted or grouped, that lets a database find matching items without reading all of them.). For each word it keeps the list of documents that contain it: (A small, fast store that keeps copies of popular data, so most reads skip the slower database.) is in documents 3, 17 and 42.
Both structures get built ahead of time, so each keystroke costs little. Every point in the letter tree can store its top few suggestions, ranked by past use, so the most common one shows first. For full search, the engine takes each word's list and keeps the documents found in every one. It then ranks those, for example by how often the words appear in each.
The problem it solves
A shop may hold millions of products, and a user wants the ten best matches for a few words. Reading every product on each search is too slow. Suggestions are harder still, because a new request arrives with almost every key press.
Why it matters
Almost every product has a search box, and users expect results while they type. A plain database query such as LIKE '%shoes%' cannot use an ordinary index, so it reads every row. Search needs its own data structures, built ahead of time.
A worked example
Scanning every row of 10,000,000 documents for one keyword checks all 10,000,000 of them. A search index instead looks up a pre-built list for that word directly. That list might hold only 4,000 matching documents, so the search touches about 10,000,000 ÷ 4,000 = 2,500 times fewer records.
Think of it like…
Think of the index at the back of a textbook. It lists each important word with the pages that use it. To find a word, you read one line, not every page.
Where this analogy stops working
A ready-made list of where each word appears is the useful part. But a person picks a book's index words once. A search index lists nearly every word, in a cleaned form, and scores the matches. It is updated as documents change, so a new document appears after a short delay.
Try it
See it working
Mechanics
How it works
Search is fast because the work is done before anyone types. The engine builds an inverted index for whole words and a trie for autocomplete, and a search only reads what they already hold.
Split and clean the text
The engine splits each document into words, called tokens. It lowercases them, drops punctuation, and often cuts words to their root, so "running" becomes "run". The same steps run on the search query, so both sides match.
Build an inverted index
Pick a case to follow belowWith this case: With no index, one search read all 60 documents to find 2.
Search box, cache redis Search box cache redis Inverted index, word → documents Inverted index word → documents Documents, 60 pages, SLOW, NOW Documents 60 pages read all 60 SLOW Results, ids in both lists Results ids in both lists - Search box — cache redis — healthy
- Inverted index — word → documents — healthy
- Documents — 60 pages — SLOW — NOW — read all 60
- Results — ids in both lists — healthy
- Lookup
- Answer
Step 1 of 2Step 1 of 2 · Documents
Watch: The engine reads all 60 documents
- What happens
- With no index, it opens each document and looks for both words.
- Why
- Nothing says in advance which documents hold a word.
- What changes
- Every search reads all 60. With a million documents, that is a million reads.
- Next
- It finds 2 documents with both words
Documents read60Watch: of 60Matches17, 42Step 1 of 2: Documents. The engine reads all 60 documents. With no index, it opens each document and looks for both words.
An inverted index maps each word to the list of documents that contain it. For example, "cache" maps to documents 3, 17 and 42. A search for two words reads two lists and keeps the ids found in both.
In the picture, someone searches for "cache (A widely used data store that keeps its data in memory, so it answers much faster than a database on disk. It is often used as a cache.)" in 60 documents. With no index, the engine opens all 60. With the inverted index, it reads two short lists, 3, 17, 42 and 17, 42, 58, and keeps the ids in both: 17 and 42. It never opens a document to find them.
A trie for autocomplete
Start, nothing typed Start nothing typed c, one letter in, NOW c one letter in here NOW ca, two letters in ca two letters in Stored at ca, top completions Stored at ca top completions - Start — nothing typed — healthy
- c — one letter in — healthy — NOW — here
- ca — two letters in — healthy
- Stored at ca — top completions — healthy
- Lookup
- Answer
Step 1 of 3Step 1 of 3 · c
Done: The user types c
- What happens
- The engine steps from the start of the trie to the node for c.
- Why
- Every word that starts with c hangs under this one node.
- What changes
- Words that start with anything else are already ruled out.
- Next
- The user types a
Nodes walked1one for each letter typedSuggestions–type moreStep 1 of 3: c. The user types c. The engine steps from the start of the trie to the node for c.
What these pictures simplify. These pictures use 60 documents and a small, stated index. A real engine holds millions of documents and also scores each match, as the last step explains. The search case study above runs live queries.
A trie is a tree where each step down adds one letter, so the path c, a, t spells "cat". To suggest as the user types, walk down the letters typed so far. Each node stores its top few popular completions, so nothing is sorted at typing time.
In the picture, the user types c, then a. The engine takes one step down for each letter, and the ca node already holds card, car and care, most typed first. Typing more letters walks further down, and the stored list gets more exact.
Rank the results
Many documents may match, so the engine scores them. A word that appears often in a document raises its score. A word that is rare across all documents counts for more than a common one. (A standard formula search engines use to rank documents by their words. A word counts more when it is rare across all documents and frequent in this one.), the default formula in Elasticsearch, is built on these two ideas.
Use it when
- Suggestions while the user types: a trie, or another index built for prefixes, answers each key press with a short walk.
- Finding words inside long text, such as articles, product pages or support tickets: an inverted index reads one list per word.
- Searching logs for an error message or a request id: a search engine such as Elasticsearch indexes each log line soon after it arrives.
Skip it when
- Looking up one row by its id, such as user:42: the database's own index already does this, with nothing extra to run.
- A value that must be right the moment it is written, such as a balance. A search index is usually a copy that is updated shortly after the database.
Check yourself
Also
More in 60 seconds
How a Bloom filter answers
A Bloom filter is a small row of bits that says an item is definitely not in a set, or probably is.
Scene 1 of 8 · Sixteen bits, all off
A Bloom filter starts as a row of 16 bits: tiny switches that are all off, or 0.
Nothing added yet
- Bit 0: off, 0
- Bit 1: off, 0
- Bit 2: off, 0
- Bit 3: off, 0
- Bit 4: off, 0
- Bit 5: off, 0
- Bit 6: off, 0
- Bit 7: off, 0
- Bit 8: off, 0
- Bit 9: off, 0
- Bit 10: off, 0
- Bit 11: off, 0
- Bit 12: off, 0
- Bit 13: off, 0
- Bit 14: off, 0
- Bit 15: off, 0
- Bits switched on
- 0
- New words that look added
- not shown yet
- Sixteen bits, all off. A Bloom filter starts as a row of 16 bits: tiny switches that are all off, or 0.
- Hash the word. To add dog, three hash functions each turn it into a bit number: 1, 3 and 5.
- Switch those bits on. Bits 1, 3 and 5 switch on, and the word dog itself is not stored anywhere.
- Add fox and bee. Adding fox and bee switches on 4 more bits; bee reuses bits 1 and 7.
- One 0 means no. To test cow, check bits 8, 11 and 13; bit 8 is 0, so cow was never added.
- All 1s means maybe. Testing fox finds bits 0, 7 and 13 all on, so fox was probably added.
- A false positive. Bear was never added, but bits 0, 11 and 13 are on anyway: a false positive.
- Bigger filters, fewer mistakes. With 7 of 16 bits on, about 8% of new words look added; more bits lower that.
- Now you try. Tap words to add them to an empty filter. The last word you tap is tested, not added. For example, tapping dog, fox, bee and bear gives this: You added dog, fox and bee. Bear: bits 0, 11 and 13 are all 1, so the filter says probably yes. Bear was never added; other words switched those bits on, so this is a false positive.
Scene 1 of 8: Sixteen bits, all off. A Bloom filter starts as a row of 16 bits: tiny switches that are all off, or 0.
Key points
- Adding an item switches on the few bits its hash functions point to.
- If any of an item's bits is 0, the item was definitely never added.
- If all its bits are 1, it was probably added, but other items may have set them.
- Search indexes and databases can check a Bloom filter first, and skip files that cannot hold the key.
Judgement
Trade-offs and how it fails
What you give up
- Performance
- A trie lookup takes one step per typed letter, written O(L) for a prefix of L letters. It does not slow down as more queries are stored. Reading the suggestions is quick only because each node already holds its top few.
- Memory
- Both structures are extra copies of the data, and they take memory or disk. Storing the top few results at every trie node saves work on each key press. It costs more space and a slower rebuild.
- Freshness
- The index is built from the main data, so it runs behind it. A new product or a newly popular query shows up only after the next update.
Failure modes
- The trie grows without limit: it stores every query anyone has typed, including one-off typos. Keep only queries typed often enough, and cap their length.
- Stale suggestions: the trie is rebuilt once a day, so a query that became popular this morning is missing until tomorrow. Rebuild more often, or keep a small trie of recent queries beside the main one.
- The index and the database disagree: a product is deleted in the database, but the update to the index fails. Search keeps showing it until the index is repaired or rebuilt.
In the real world
- Google's help page on autocomplete says its predictions reflect real searches, and that it also weighs language, location and trending interest.
- Elasticsearch's documentation calls its search near real-time. By default it refreshes an active index every second, so a new document is not searchable at once.
- Elasticsearch, OpenSearch and Solr are all built on Apache Lucene, an open-source library whose core structure is an inverted index.
Trade-offs to be ready to discuss: Trie vs inverted index
Check yourself
Interview
What interviewers look for
- Say where the sorting happens: "Each trie node stores its top five completions, worked out when the trie is built. A key press only walks down and reads them."
- Say how the counts stay fresh: "Searches go to a log such as (An open-source system that stores streams of messages in order on disk. Many services can read the same messages, each at its own pace.). A job counts them and rebuilds the trie every few minutes or hours, depending on how fresh it must be."
- Keep the two structures apart. A trie answers "what starts with these letters". An inverted index answers "which documents contain this word".
- Say the search index is a copy: "The database stays the source of truth, and the index is updated from it a little later."
Say it out loud: How many steps does it take to find the node for a prefix of L letters in a trie?
Expected depth by interview level
Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.
- JuniorUseful
- Why a search index differs from a database query.
- MidExpected
- Inverted indexes, and tries for typeahead.
- SeniorExpected
- Indexing pipelines, freshness and ranking at scale.
- StaffUseful
- Search as a shared platform.
Practice
Apply it
Three harder questions
The first two use the idea on a new case. The last asks you to judge a design.
Apply it
Apply it
Judge a design
Go deeper
Sources and further reading
First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsText analysisElastic documentationHow text is split into terms before it goes into the inverted index, and why that changes what matches.
- Official docsAutocompleteOpenSearch documentationFour real ways to suggest words as the user types, with the cost of each.
- Official docsWhat is Apache LuceneApache LuceneThe search library under Elasticsearch and OpenSearch, with its indexing and query features.