How to Implement Search As You Type in Elasticsearch
To implement
search as you type in Elasticsearch, use the search_as_you_type field type which indexes prefixes for fast autocomplete. Then query with a match or multi_match query on that field to get instant suggestions as the user types.Syntax
The search_as_you_type field type is designed for autocomplete. It indexes text with prefixes to support fast prefix matching. You define it in your index mapping like this:
search_as_you_type: The field type for autocomplete.analyzer: Controls how text is broken down.max_shingle_size: Controls phrase suggestions.
To query, use a match or multi_match query on the search_as_you_type field.
json
{
"mappings": {
"properties": {
"title": {
"type": "search_as_you_type"
}
}
}
}Example
This example creates an index with a search_as_you_type field called title, indexes some documents, and runs a search-as-you-type query to get autocomplete suggestions.
json
PUT /books
{
"mappings": {
"properties": {
"title": {
"type": "search_as_you_type"
}
}
}
}
POST /books/_doc/1
{
"title": "Elasticsearch Basics"
}
POST /books/_doc/2
{
"title": "Elasticsearch Advanced"
}
POST /books/_doc/3
{
"title": "Learning Elasticsearch"
}
GET /books/_search
{
"query": {
"multi_match": {
"query": "Elas",
"type": "bool_prefix",
"fields": [
"title",
"title._2gram",
"title._3gram"
]
}
}
}Output
{
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"hits": [
{"_source": {"title": "Elasticsearch Basics"}},
{"_source": {"title": "Elasticsearch Advanced"}},
{"_source": {"title": "Learning Elasticsearch"}}
]
}
}
Common Pitfalls
Common mistakes when implementing search as you type include:
- Using
texttype instead ofsearch_as_you_type, which is less efficient for autocomplete. - Not using
bool_prefixtype inmulti_matchquery, which is needed for prefix matching. - Forgetting to include the
_2gramand_3gramsubfields in the query fields array. - Not refreshing the index after indexing documents, so new data doesn't appear in search immediately.
json
/* Wrong query without bool_prefix */ GET /books/_search { "query": { "match": { "title": "Elas" } } } /* Correct query with bool_prefix and ngram fields */ GET /books/_search { "query": { "multi_match": { "query": "Elas", "type": "bool_prefix", "fields": ["title", "title._2gram", "title._3gram"] } } }
Quick Reference
- Field type:
search_as_you_typefor autocomplete indexing. - Query type:
multi_matchwithbool_prefixfor prefix search. - Include subfields:
_2gramand_3gramin query fields. - Refresh index: Use
POST /index/_refreshafter indexing.
Key Takeaways
Use the search_as_you_type field type for efficient autocomplete indexing.
Query with multi_match and bool_prefix type to enable prefix matching.
Include the _2gram and _3gram subfields in your query fields for better results.
Always refresh your index after adding documents to see immediate search results.
Avoid using plain text fields and match queries for search-as-you-type functionality.