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

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.

Queries people typed
QueryTimes typed
card90
car70
dog60
care40
door30
cat25
cap10
Steps taken, one per letter
0
Queries stored
7
  1. What people typed. A search box has seen 7 queries, each with how often people typed it.
  2. One letter per node. A trie stores them letter by letter, so queries that start the same share a path.
  3. Type c. Typing c takes one step down, and everything below that node starts with c.
  4. Then a. After c and a, the node already knows its top three: card, car and care.
  5. Some queries end early. car is a full query, yet its path goes on to card and care.
  6. Speed depends on letters. Each letter is one step, so the work depends on how much you type, not on how many queries exist.
  7. 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

  1. A trie stores text one letter per node, so queries that start the same share one path.
  2. Typing walks one node per letter, then reads the suggestions kept at that node.
  3. The work grows with the letters typed, not with the number of queries stored.
  4. 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 makes that possible. It is a tree that adds one letter at each level, so everything beginning with ca hangs under a single . Searching for whole words inside documents uses another structure, the inverted . For each word it keeps the list of documents that contain it: 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

Case study · Live model

How search autocomplete behaves

As a user types, the browser asks for the 5 most searched phrases that start with the letters so far, the prefix. The answers come from a tree of 500 phrases, with a cache in front. A job counts past searches and builds a new tree. Change when the browser asks, what the tree stores, or start a trend.

Try it

Lab time 3.0 s
kept?top 5?new treeBrowsers, 2 searches a secondBrowsers2 searches a secondask on every keySuggest API, 58 requestsSuggest API58 requests58 key pressesPrefix cache, 43 prefixes keptPrefix cache43 prefixes keptfor 30 s eachTree servers, 500 phrases in a treeTree servers500 phrases in a treetop 5 kept at each nodeSearch log, 0 new searchesSearch log0 new searchesnot counted yetCounting job, rebuilds every 20 sCounting jobrebuilds every 20 snext in 17.0 s
  • Browsers — 2 searches a second — healthy — ask on every key
  • Suggest API — 58 requests — healthy — 58 key presses
  • Prefix cache — 43 prefixes kept — healthy — for 30 s each
  • Tree servers — 500 phrases in a tree — healthy — top 5 kept at each node
  • Search log — 0 new searches — healthy — not counted yet
  • Counting job — rebuilds every 20 s — healthy — next in 17.0 s
  • Suggestions for a prefix, please
  • The cache has the answer
  • Look the prefix up in the tree
  • The top 5
  • A finished search goes into the log
  • The log is counted
Requests per search
–
over the last 15 s; 0 key presses sent no request
From the cache
22%
of requests answered there; the rest walk the tree
Steps for one lookup
5
in the tree, last 3 s
Answers too late
0/ 55
the user had typed on
Trending phrase
–
press "Start a trend"
Next rebuild
17.0 s
0 searches wait to be counted

Numbers add up:58 key presses = 58 requests + 0 skipped + 0 waiting for a pause · 58 requests = 12 from the cache + 43 from the tree + 3 on the wayThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Typing
2 a second

The browser asks only when no key was pressed for 0.2 s.

The tree and the cache

Off: a lookup visits every phrase below the node and picks the 5 best each time.

The answer for a prefix is kept for a while, so the next request for it skips the tree.

30 s
every 20 s

Suggestions for "se" now

PlacePhraseSearches counted
1service pipeline21
2service server17
3service router14
4service limit13
5service store8

This is what the tree answers for the prefix "se". The counts change only when the tree is rebuilt.

Key presses and requests, each second
Key pressesRequests
012.52537.5501s2s3s
Show data table
TimeKey pressesRequests
1s00
1s44
2s1818
2s2020
3s3232
3s4242

What just happened

Nothing yet. Start traffic or run an experiment.

What this model simplifies
  • There are 500 phrases, made from 20 first words and 25 second words. A real service knows hundreds of millions, in many languages.
  • The tree is rebuilt every few seconds here. Real services rebuild it every few hours or once a day, and add a faster path for phrases that start trending.
  • Every search counts the same. Real rankings give more weight to recent searches, and remove phrases that should not be suggested.
  • One tree answers everyone. Real suggestions also depend on the place, the language and what the user searched before.
  • A lookup here costs a few milliseconds at most. With hundreds of millions of phrases, a visit to every phrase below a node would take far too long.
  • The cache is one box. A real service also lets the browser and servers near the user keep answers.

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.

  1. 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.

  2. Build an inverted index

    Pick a case to follow below

    With this case: With no index, one search read all 60 documents to find 2.

    Search box, cache redisSearch boxcache redisInverted index, word → documentsInverted indexword → documentsDocuments, 60 pages, SLOW, NOWDocuments60 pagesread all 60SLOWResults, ids in both listsResultsids 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 2

    Step 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 read
    60
    Watch: of 60
    Matches
    17, 42

    Step 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 " 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.

  3. A trie for autocomplete

    Start, nothing typedStartnothing typedc, one letter in, NOWcone letter inhereNOWca, two letters incatwo letters inStored at ca, top completionsStored at catop 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 3

    Step 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 walked
    1
    one for each letter typed
    Suggestions
    –
    type more

    Step 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.

  4. 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. , 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

What does an inverted index map?

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.

The Bloom filter: 16 bits

Nothing added yet

  1. Bit 0: off, 0
  2. Bit 1: off, 0
  3. Bit 2: off, 0
  4. Bit 3: off, 0
  5. Bit 4: off, 0
  6. Bit 5: off, 0
  7. Bit 6: off, 0
  8. Bit 7: off, 0
  9. Bit 8: off, 0
  10. Bit 9: off, 0
  11. Bit 10: off, 0
  12. Bit 11: off, 0
  13. Bit 12: off, 0
  14. Bit 13: off, 0
  15. Bit 14: off, 0
  16. Bit 15: off, 0
Bits switched on
0
New words that look added
not shown yet
  1. Sixteen bits, all off. A Bloom filter starts as a row of 16 bits: tiny switches that are all off, or 0.
  2. Hash the word. To add dog, three hash functions each turn it into a bit number: 1, 3 and 5.
  3. Switch those bits on. Bits 1, 3 and 5 switch on, and the word dog itself is not stored anywhere.
  4. Add fox and bee. Adding fox and bee switches on 4 more bits; bee reuses bits 1 and 7.
  5. One 0 means no. To test cow, check bits 8, 11 and 13; bit 8 is 0, so cow was never added.
  6. All 1s means maybe. Testing fox finds bits 0, 7 and 13 all on, so fox was probably added.
  7. A false positive. Bear was never added, but bits 0, 11 and 13 are on anyway: a false positive.
  8. Bigger filters, fewer mistakes. With 7 of 16 bits on, about 8% of new words look added; more bits lower that.
  9. 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

  1. Adding an item switches on the few bits its hash functions point to.
  2. If any of an item's bits is 0, the item was definitely never added.
  3. If all its bits are 1, it was probably added, but other items may have set them.
  4. 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

Why are autocomplete suggestions often rebuilt in batches, such as every hour?

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 . 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?

Autocomplete stores the top 5 searches at every node of the trie. What does that buy?

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

"cache" is in documents 3, 17 and 42. "redis" is in documents 17, 42 and 90. Which documents match a search for both words?

Apply it

A document says "Running servers". The engine lowercases words and cuts them to their root. A user searches for "RUN server". Does it match?

Judge a design

Autocomplete rebuilds its trie once a day. A new phone launches at 9 am and everyone searches for it. Which change helps most?

Next: replication and sharding, the two ways to spread a database over several machines when one is not enough.

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.