Modern search systems don’t just find exact matches, they understand partial words, typos, and phrases as you type. Elasticsearch makes this possible with a mix of analyzers and special queries like N-Gram, Reverse, Fuzzy, and Search-as-you-type.
In this article, we’ll learn how these techniques work, when to use each, and how to combine them for a fast and smart search experience.
Why “Advanced” Text Search?
In real-world apps, users rarely type exact words.
They type fast, make mistakes, or expect results before finishing the query.
For example:
- “iph”, should match “iPhone 15 Pro”
- “iphon”, should still match “iPhone” (even with typo)
- “.pdf”, should find “report.pdf”
To make that work, Elasticsearch uses special analyzers and queries under the hood.
N-Gram Analyzer — Matching Inside Words
The N-Gram analyzer splits text into small overlapping pieces called n-grams.
This allows search to match any part of a word, not just the beginning.
Example
Text: "search"
With min_gram: 3, max_gram: 5, tokens become:
["sea", "ear", "arc", "rch"]
So a user typing “arc” still finds “search”.
Example Mapping
PUT ngram_index
{
"settings": {
"analysis": {
"tokenizer": {
"my_ngram": {
"type": "ngram",
"min_gram": 3,
"max_gram": 5
}
},
"analyzer": {
"my_ngram_analyzer": {
"tokenizer": "my_ngram",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"properties": {
"name": { "type": "text", "analyzer": "my_ngram_analyzer" }
}
}
}
Now when you search:
GET ngram_index/_search
{
"query": { "match": { "name": "arc" } }
}
It matches “search”, “arctic”, “arcade”, etc.
Trade-off
N-Gram creates many tokens, bigger index size.
Use it only for short fields like names or titles, not large documents.
Edge N-Gram, Perfect for Autocomplete
Edge N-Gram works like N-Gram, but it only creates tokens from the start of the word.
This makes it ideal for prefix matching (autocomplete).
Text: "search"
Edge N-Gram tokens (min_gram=2, max_gram=5):
["se", "sea", "sear", "searc"]
So when a user types “sear”, it matches “search”.
Example Mapping
PUT edge_index
{
"settings": {
"analysis": {
"tokenizer": {
"edge_tokenizer": {
"type": "edge_ngram",
"min_gram": 2,
"max_gram": 10
}
},
"analyzer": {
"autocomplete": {
"tokenizer": "edge_tokenizer",
"filter": ["lowercase"]
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
}
Now, as you type:
- “se”: matches “search”, “service”, “secure”
- “serv”: matches “server”, “service”
Great for instant autocomplete search bars.
