Topic F9
Autocomplete
A trie, top-K and debounce together: suggestions on every keystroke.
Watch: every letter typed moves one step down the tree of letters. Every word below it is a possible suggestion.
- finished / the result
- no longer used
In the browser or on the server
- Small lists (up to thousands): send them all to the browser once, then search there. No network per keystroke, so suggestions appear instantly. For a few thousand items, even a plain filter is fast enough.
- Large lists (millions of products, addresses): search on the server with a dedicated index, such as a trie or a prefix index in Elasticsearch, Meilisearch or PostgreSQL (
LIKE 'ban%'with a B-tree index, or pg_trgm for matching mid-word).
Code, for programmersA search box that's polite to the server
function useSuggestions(text) {
const q = useDebounced(text.trim().toLowerCase(), 200); // wait for a pause
return useQuery({
queryKey: ["suggest", q], // each prefix cached once
queryFn: ({ signal }) => // signal cancels stale requests
fetch(`/api/suggest?q=${encodeURIComponent(q)}`, { signal }).then((r) => r.json()),
enabled: q.length >= 2, // skip one-letter searches
staleTime: 5 * 60_000,
});
}Details that make it feel right
- Normalise: lowercase, trim spaces, and fold accents ("é" and "e") in both the data and the input.
- Ordering: popularity, the user's history, or nearness. Store a top-K at each trie node so you never walk a whole branch.
- Keyboard and accessibility: up/down arrows, Enter, Escape, and the ARIA combobox pattern (
role="combobox",aria-activedescendant). - Highlight the matching part of each suggestion, so users see straight away why it appeared.
Quiz
Why does a trie suit autocomplete?
A list of 300 country names. The simplest option that's still fast?
The user typed 'ban' but sees suggestions for 'ba'. The cause?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.