Sub topic 13
Adding Autocomplete
Autocomplete (also called typeahead) shows suggestions while the user is still typing. This chapter assumes you know how an inverted index and text analysis work, and that you have seen query design with filters and pagination.
Why normal search does not fit
A normal search index stores whole terms such as "running". A user who has typed "runn" has not typed a term yet, so an exact term lookup finds nothing. Autocomplete must match on a prefix, and it must answer fast. Users expect suggestions within about 100 ms of each keystroke.
Three common approaches
| Approach | How it works | Trade-off |
|---|---|---|
| Prefix query | Scan the term dictionary for terms starting with the prefix | Simple, but slow on large fields and no typo tolerance |
| Edge n-grams at index time | Analyze each term into its prefixes ("run", "runn", "runni"...) | Fast lookups, larger index |
| Dedicated suggester | A purpose-built structure (for example a completion field) | Fastest, but limited ranking and filtering |
Edge n-grams are the usual starting point. They reuse the inverted index you already have, so every query feature still works. The cost is more terms per document, which means more disk and slower indexing.
Mapping for edge n-grams
Use a different analyzer at search time than at index time. The query text "runn" must stay as "runn". If it were also split into n-grams, it would match any term that shares a short prefix such as "ru", and suggestions would become noisy.
PUT /products
{
"settings": {
"analysis": {
"filter": {
"edge_filter": { "type": "edge_ngram", "min_gram": 2, "max_gram": 15 }
},
"analyzer": {
"autocomplete_index": {
"tokenizer": "standard",
"filter": ["lowercase", "edge_filter"]
},
"autocomplete_search": {
"tokenizer": "standard",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"fields": {
"suggest": {
"type": "text",
"analyzer": "autocomplete_index",
"search_analyzer": "autocomplete_search"
}
}
}
}
}
}The name field keeps its normal analysis for full search. The name.suggest subfield holds the prefix terms. Setting min_gram to 2 avoids one-letter prefixes that match almost everything.
Query the subfield:
GET /products/_search
{
"query": { "match": { "name.suggest": "runn" } },
"size": 5
}Design decisions
- Return few results. Five to ten suggestions is enough. Use a small
size. - Rank by popularity. BM25 on short names ranks poorly. Blend in a signal such as past search counts or sales.
- Debounce on the client. Wait 150 to 300 ms after the last keystroke before sending a request. This cuts query load sharply.
- Suggest from a curated source when quality matters. Product names can be messy. Many systems build suggestions from popular past queries instead.
- Apply the same access control. Suggestions can leak titles of documents the user may not see, so use the same filters as the main search.
Failure modes
- Index growth. A long
max_grammultiplies stored terms. Keep it near the longest prefix users will type. - Latency spikes. Autocomplete fires far more often than full search. Give it its own cache or its own replicas if it competes for resources.
- Stale or out-of-order responses. A slow response for "ru" can arrive after the response for "runn". The client should ignore any response that does not match the current input.
Exercise
Why should the autocomplete field use a different analyzer at search time than at index time?
Show answer
The index analyzer creates edge n-grams so that prefixes are stored as terms. The search analyzer must not do this, because the typed prefix would also be split into short n-grams and match unrelated terms. Using a plain analyzer at search time keeps "runn" as one term that matches the stored prefix "runn".
Exercise
Suggestions for "ru" appear after suggestions for "runn" on the screen. Name the cause and one fix.
Show answer
Responses arrived out of order because the earlier request was slower. The client should discard any response whose query no longer matches the current input, or cancel the in-flight request when a new keystroke arrives.