How to Highlight Search Results in Elasticsearch
To highlight search results in
Elasticsearch, use the highlight field in your search query. This field specifies which fields to highlight and how, so matched terms appear wrapped in tags like <em> in the results.Syntax
The highlight section in an Elasticsearch query defines which fields to highlight and the tags to use for wrapping matched terms.
- fields: The fields to highlight.
- pre_tags: Tags to insert before the matched term (default is
<em>). - post_tags: Tags to insert after the matched term (default is
</em>).
json
{
"query": {
"match": {
"field_name": "search text"
}
},
"highlight": {
"fields": {
"field_name": {}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"]
}
}Example
This example searches for the word "quick" in the content field and highlights the matched word by wrapping it with <strong> tags.
json
{
"query": {
"match": {
"content": "quick"
}
},
"highlight": {
"fields": {
"content": {}
},
"pre_tags": ["<strong>"],
"post_tags": ["</strong>"]
}
}Output
{
"hits": {
"hits": [
{
"_source": {
"content": "The quick brown fox jumps over the lazy dog"
},
"highlight": {
"content": ["The <strong>quick</strong> brown fox jumps over the lazy dog"]
}
}
]
}
}
Common Pitfalls
- Not specifying the
highlightfield in the query will return results without highlights. - Highlighting fields that are not stored or analyzed properly may return empty highlights.
- Using incorrect field names in
highlight.fieldscauses no highlights to appear. - For multi-field mappings, highlight the correct subfield (e.g.,
field.keywordis not suitable for highlighting).
json
{
"query": {
"match": {
"content": "quick"
}
},
"highlight": {
"fields": {
"wrong_field": {}
}
}
}
// Correct usage:
{
"query": {
"match": {
"content": "quick"
}
},
"highlight": {
"fields": {
"content": {}
}
}
}Quick Reference
- highlight.fields: Specify fields to highlight.
- pre_tags and post_tags: Customize highlight wrappers.
- Highlight only analyzed text fields.
- Use
require_field_matchto control highlighting behavior across fields.
Key Takeaways
Use the
highlight field in your Elasticsearch query to enable result highlighting.Specify which fields to highlight inside
highlight.fields with optional custom tags.Highlighting works best on analyzed text fields, not keyword or numeric fields.
Common mistakes include wrong field names or missing the highlight section entirely.
Customize
pre_tags and post_tags to change how highlights appear.