Search Autocomplete
Tries and top results.
You type b l u into Shoply's search box, and suggestions appear instantly. Blue mug, blue towel, bluetooth speaker. They must appear in under a hundred milliseconds, as you type every letter.

- Type b-l-u
- Suggestions appear
- Under 100 ms, every letter
A trie with top results
The classic structure is a trie, a tree where each step is one letter. Every node stores the most popular searches that start with that prefix. So answering is just walking down a few letters, and reading the stored list. Run it. Typing b l u returns the top three searches, ordered by how often people search them.
searches = {"blue mug": 900, "blue towel": 400, "bluetooth speaker": 750,
"black pot": 300, "blue lamp": 120}
trie = {}
for phrase, count in searches.items():
node = trie
for ch in phrase:
node = node.setdefault(ch, {"_top": []})
node["_top"] = sorted(node["_top"] + [(count, phrase)], reverse=True)[:3]
def suggest(prefix):
node = trie
for ch in prefix:
node = node.get(ch, {"_top": []})
return [p for _, p in node["_top"]]
print("bl ->", suggest("bl"))
print("blu ->", suggest("blu"))bl -> ['blue mug', 'bluetooth speaker', 'blue towel'] blu -> ['blue mug', 'bluetooth speaker', 'blue towel']
Why store the top results
Storing the top results in every node is the key trick. Without it, we'd have to search the whole subtree below the prefix, and sort, on every keystroke. With it, a suggestion is a few steps down the tree and one read. We trade memory, and slower updates, for very fast reads.
| key | value |
|---|---|
| Each node | stores its top 3–10 |
| Query | walk the prefix, read |
| Cost | more memory |
| Updates | rebuilt periodically |
Summary
A trie stores phrases letter by letter, and keeping the top results at every node makes suggestions instant. Next, running autocomplete at scale.
Key takeaways- One letter per step
- Top results in each node
- Fast reads, slow updates