Sub topic 13
Adding autocomplete
Autocomplete (also called typeahead) shows suggestions while the user is still typing. This chapter covers the three common designs, the trade-offs between them, and the operational limits that decide which one fits. It assumes you know the earlier chapters on text analysis, index and mapping design, and query design. It also assumes you are comfortable with basic REST calls and with the idea of a latency budget.
What autocomplete asks of the system
A normal search request runs after the user presses Enter. Autocomplete runs on almost every keystroke, so it differs in four ways.
- Latency. Suggestions must appear before the next keystroke, so aim for a response in well under 100 ms at the server, plus network time.
- Volume. One user typing a 12-character query can send 12 requests. Autocomplete traffic is often several times the traffic of full search.
- Input is incomplete. The last word is a prefix, such as
runn, not a full term. A standard analyzer produces the termrunn, which no document contains, so a plainmatchquery finds nothing. - Output is different. The user wants a short list of likely completions, not ten ranked documents with all their fields.
The first two points push you toward cheap queries and caching. The last two push you toward a dedicated field or index built for prefixes.
Three designs
There are three common ways to produce suggestions. They differ in what they suggest and how they store it.
| Design | What it suggests | Typical mechanism | Main weakness |
|---|---|---|---|
| Prefix query on the main field | Terms or documents that start with the typed text | `prefix` or `match_phrase_prefix` query | Slow on large term sets, no typo tolerance |
| Index-time n-grams | Documents whose words contain the typed fragment | `edge_ngram` token filter | Larger index, fixed maximum length |
| Dedicated suggester | Curated phrases, such as popular queries or product names | Completion suggester or a separate suggestions index | Another dataset to build and refresh |
Prefix queries
The simplest option is to query the existing field for terms that begin with what the user typed. The engine walks its sorted term dictionary, finds the terms in the prefix range, and unions their postings.
This works for small indexes. Cost grows with the number of matching terms. A one-letter prefix such as r can expand to thousands of terms, so require a minimum prefix length (often 2 or 3 characters) before you send a request. Prefix queries also run at query time, so you pay the cost on every keystroke.
Edge n-grams
An edge n-gram is a prefix of a token. The token running produces ru, run, runn, runni, runnin, running when the minimum gram size is 2. If you store these as terms at index time, a query for runn becomes an ordinary exact term lookup in the inverted index. You move the work from query time to index time.
The mapping needs two analyzers. The index analyzer generates grams. The search analyzer must not, otherwise the query runn is itself split into ru, run, runn and matches too much.
PUT /products-suggest
{
"settings": {
"analysis": {
"filter": {
"edge_2_15": { "type": "edge_ngram", "min_gram": 2, "max_gram": 15 }
},
"analyzer": {
"autocomplete_index": {
"tokenizer": "standard",
"filter": ["lowercase", "edge_2_15"]
},
"autocomplete_search": {
"tokenizer": "standard",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "autocomplete_index",
"search_analyzer": "autocomplete_search"
}
}
}
}The query is then a normal match:
GET /products-suggest/_search
{
"query": { "match": { "name": "running sh" } },
"_source": ["name"],
"size": 5
}With the default or operator, running sh matches documents containing either running or any word starting with sh. Set "operator": "and" on the match clause so every typed word must be present. This keeps the list focused.
The cost of n-grams is index size. A word of length L with min_gram 2 produces L − 1 terms, capped by max_gram. Choose max_gram carefully. If it is 15, a user typing a 20-character word still matches, because the search analyzer sends the full 20-character term and the index holds only grams up to 15 characters. That term then finds nothing. Either truncate the query to max_gram with a truncate filter in the search analyzer, or accept that very long fragments return no suggestions.
Keep n-gram fields separate from your main search fields. Do not run BM25 relevance for the main query over a gram field. Grams inflate term frequencies and distort scores.
Dedicated suggestions
The first two designs suggest documents. Many products instead suggest phrases: popular queries, category names, or product titles. A completion suggester stores phrases in a compact in-memory structure (a finite state transducer in Elasticsearch) that is built for fast prefix lookups. Alternatively, you can build an ordinary index of suggestion records, each with a phrase, a weight, and optional context.
PUT /suggestions
{
"mappings": {
"properties": {
"phrase": {
"type": "search_as_you_type"
},
"weight": { "type": "integer" }
}
}
}The search_as_you_type field type creates the gram subfields for you, so you avoid hand-written analyzers. Query it with a multi_match of type bool_prefix over the field and its subfields. Combine the text score with weight using a function_score or rank_feature clause, so popular phrases come first.
A dedicated suggestions index has a real benefit: you control the vocabulary. It can exclude rare typos, out-of-stock products, or offensive terms. The cost is a second pipeline. Something must compute the phrases and weights, often from query logs, and refresh them on a schedule.
Ranking suggestions
Text relevance is a weak signal for autocomplete because all candidates match the prefix equally well. Useful signals are:
- Popularity. How often users searched for or clicked this phrase. Use a stored weight, not a live count.
- Recency. Boost recent or trending phrases, with a decay.
- Business value. In-stock items, items in the user's region, or sponsored entries.
- Personalization. The user's recent searches, if privacy rules allow.
Keep the scoring formula simple. Suggestions are judged in a few hundred milliseconds, and a complex ranking is hard to debug.
Typos
Users make mistakes while typing quickly. Fuzzy matching (edit distance) helps, but it multiplies cost on prefix queries. Elasticsearch's completion suggester supports a fuzzy option with a small edit distance. For n-gram setups, allow fuzziness only after the prefix reaches 3 or 4 characters, and set prefix_length so the first characters must match exactly. This limits the number of expanded terms.
The request path
The diagram shows where the work happens in a typical deployment.
Three techniques keep the load manageable.
- Debounce on the client. Wait 100 to 200 ms after the last keystroke before sending a request. This removes most intermediate requests.
- Cancel stale requests. If the user types another character, abort the in-flight request or ignore its response. Responses can arrive out of order, so a late reply for
rumust not replace the reply forrunn. Tag each request with the query string and compare it before rendering. - Cache short prefixes. The number of distinct 1-, 2-, and 3-character prefixes is small, and they account for a large share of traffic. A cache with a TTL of one minute or more absorbs most of it. Longer prefixes have a long tail and a lower hit rate.
A content delivery network can cache suggestions for anonymous users. If suggestions are personalized or permission-filtered, cache per user or skip the shared cache.
Edge cases and gotchas
- Permissions. Suggestions can leak information. If a user can't view a document, its title must not appear as a suggestion. Apply the same filters as for full search, or build suggestions only from public data.
- Stale entries. A suggestion for a deleted or out-of-stock item leads to a dead end. Because of eventual consistency, accept a small delay, but remove deleted items from the suggestions index through the same sync pipeline.
- Normalization mismatch. If the suggestion analyzer lowercases and strips accents, the displayed text must still come from the original, un-analyzed field. Store the display string in
_sourceand return that. - Stemming. Do not stem the gram field. A stemmed
runningbecomesrun, and the user who typedrunnifinds nothing. - Short queries. An empty or one-character prefix gives poor suggestions. Show recent searches or trending phrases instead of querying.
- Language and tokenization. Edge n-grams over whitespace-free languages need a language-specific tokenizer. Test with real input.
- Reindexing. Changing
min_gramormax_gramchanges the analyzer, so it requires a full reindex of that index. Keeping suggestions in their own index limits the blast radius.
Failure behavior
Because autocomplete is optional, the right failure mode is to fail quietly. Set a short timeout (for example 200 ms) on the suggestion call. On timeout or error, return an empty list. Do not retry on every keystroke. Retries would multiply load on a service that is already struggling. Rate-limit per user or per IP, since this endpoint is easy to abuse and cheap to call in a loop.
Choosing a design
- Use prefix queries for a small catalog or a prototype, with a minimum prefix length.
- Use edge n-grams when you want to suggest actual documents or titles from the main data, and you accept a larger index.
- Use a dedicated suggester or suggestions index when you need curated phrases, popularity ranking, or strict control of the vocabulary, and you can maintain the extra pipeline.
Many systems combine them: a suggestions index for phrases and, below it, a few document results from an n-gram field.
Exercise
A team adds an edgengram filter (mingram 2, max_gram 10) to the name field and uses the same analyzer at search time. Typing shoe returns products such as "Shelf organizer" and "Showcase lamp". What is the cause, and what is the fix?
Show answer
Because the search analyzer also generates edge n-grams, the query shoe is split into sh, sho, and shoe. Any document containing a term sh or sho matches, which includes words that merely start with those letters. Fix it by setting a separate search_analyzer without the edge_ngram filter, so the query stays as the single term shoe. Using "operator": "and" on multi-word queries also tightens results.
Exercise
Your suggestions endpoint receives 40,000 requests per second at peak, and most requests have prefixes of 1 to 3 characters. Name two changes that cut load without changing the index, and say why each works.
Show answer
Debounce on the client, so a pause in typing is required before a request is sent, which removes intermediate keystroke requests. Cache responses for short prefixes with a TTL, because few distinct short prefixes exist and each is requested very often, giving a high hit rate. Requiring a minimum prefix length of 2 or 3 also helps.