Highlighting matched text helps you see exactly where your search words appear in results. It makes reading easier and faster.
0
0
Highlighting matched text in Elasticsearch
Introduction
You want to show users which parts of a document matched their search.
You need to emphasize keywords in search results on a website.
You want to improve user experience by making search hits clear.
You are building a search interface that shows snippets with highlighted terms.
Syntax
Elasticsearch
{
"query": {
"match": {
"field_name": "search text"
}
},
"highlight": {
"fields": {
"field_name": {}
}
}
}The highlight section tells Elasticsearch to mark matched words.
You specify which fields to highlight inside fields.
Examples
Highlight matches of the word "apple" in the
content field.Elasticsearch
{
"query": {
"match": {
"content": "apple"
}
},
"highlight": {
"fields": {
"content": {}
}
}
}Highlight matches in the
title field using custom HTML tags <em> and </em>.Elasticsearch
{
"query": {
"match": {
"title": "Elasticsearch"
}
},
"highlight": {
"fields": {
"title": {
"pre_tags": ["<em>"],
"post_tags": ["</em>"]
}
}
}
}Highlight matches in both
title and content fields for a multi-field search.Elasticsearch
{
"query": {
"multi_match": {
"query": "search text",
"fields": ["title", "content"]
}
},
"highlight": {
"fields": {
"title": {},
"content": {}
}
}
}Sample Program
This query searches for "quick brown fox" in the description field and highlights the matched words in the results.
Elasticsearch
{
"query": {
"match": {
"description": "quick brown fox"
}
},
"highlight": {
"fields": {
"description": {}
}
}
}OutputSuccess
Important Notes
Highlighting adds extra data to your search results under the highlight key.
You can customize the tags used to wrap matched text with pre_tags and post_tags.
Highlighting can slow down search performance if used on large fields or many fields.
Summary
Highlighting shows matched words clearly in search results.
Use the highlight section in your query to enable it.
You can highlight one or more fields and customize the highlight tags.