A search-as-you-type field helps users find what they want quickly by showing results while they type. It makes searching faster and easier.
0
0
Search-as-you-type field in Elasticsearch
Introduction
When building a website search box that shows suggestions as you type.
When creating a product catalog where users can find items quickly.
When making a contact list that filters names instantly.
When you want to improve user experience by reducing typing effort.
When you want to handle partial words or prefixes in search queries.
Syntax
Elasticsearch
PUT /my_index
{
"mappings": {
"properties": {
"my_field": {
"type": "search_as_you_type"
}
}
}
}The search_as_you_type field type creates special subfields to support fast prefix matching.
You use this field type in your index mapping before adding documents.
Examples
This creates a
name field that supports search-as-you-type for product names.Elasticsearch
PUT /products
{
"mappings": {
"properties": {
"name": {
"type": "search_as_you_type"
}
}
}
}This query searches for terms starting with "iph" in the
name field and its subfields.Elasticsearch
GET /products/_search
{
"query": {
"multi_match": {
"query": "iph",
"type": "bool_prefix",
"fields": [
"name",
"name._2gram",
"name._3gram"
]
}
}
}Sample Program
This example creates an index called library with a title field that supports search-as-you-type. It adds two books and then searches for titles starting with "Grea".
Elasticsearch
PUT /library
{
"mappings": {
"properties": {
"title": {
"type": "search_as_you_type"
}
}
}
}
POST /library/_doc/1
{
"title": "The Great Gatsby"
}
POST /library/_doc/2
{
"title": "Great Expectations"
}
GET /library/_search
{
"query": {
"multi_match": {
"query": "Grea",
"type": "bool_prefix",
"fields": [
"title",
"title._2gram",
"title._3gram"
]
}
}
}OutputSuccess
Important Notes
Search-as-you-type fields create hidden subfields with n-grams to speed up prefix searches.
Use multi_match with bool_prefix type to query these fields effectively.
Remember to reindex your data after changing mappings.
Summary
Search-as-you-type fields help users find matches while typing.
Define the field with type: search_as_you_type in your mapping.
Use multi_match queries with bool_prefix to search these fields.