Recently, I'm using Elasticsearch for my system. The business requirement is to get questions that both questions' title and answers' content include the key words, also want to highlight the key in title and content. I'm a newbie of ES. after many times attempts, summary the use cases that I met. Hope it can help you out when you got same cases.
- how to highlight key words in "has_child" or "has_parent" query?
When you use has_child or has_parent to get matched child/parent documents, the highlight can be got through "inner hits" , please see example:
Input
"has_child": {
"type": "<the child type/table>",
"query": {
"multi_match": {
"query": "<key words>",
"fields": [<the child type's fields>]
}
},
"inner_hits": {
"highlight": {
"fields": {
"details":{
"type": "plain",
"force_source" : true,
"fragment_size": 20,
"number_of_fragments": 3
}
}
},
"size":1,
"sort": { "<the child field that used to sort>": "desc"}
}
}
}
Output
"inner_hits": {
"my_answers": {
"hits": {
"total": 2,
"max_score": null,
"hits": [
{
"_index": "ycx_education",
"_type": "my_answers",
"_id": "1",
"_score": null,
"_routing": "001",
"_parent": "001",
"_source": {
"details": "日系车的底盘轻,车身金属偏薄,所以省油。其他优点就是内饰比较精致",
"praiseCount": 100,
"commentCount": 30
},
"highlight": {
"details": [
"日<em>系</em>车的底盘轻,车身金属偏薄,所以省油"
]
},
"sort": [
100
]
}
]
}
}
`
2. How to highlight key words in "filtered" query?
When you use _filtered_ (maybe it also works for other queries) query, and want to highlight the key words in the _filtered_ query result. The key to achieve this is "highlight_query".
**Input**
`
"query": {
"filtered": {
"query": {
......
},
"filter": {
......
}
}
},
"highlight": {
"fields": {
"title": { "number_of_fragments": 0 },
"description": {"number_of_fragments": 3}
},
"highlight_query": {
"bool": {
"should": [
{
"query_string":
{
"fields": [ "title", "description"],
"query": "德系"
}
}
]
}
}
}
Output
It's same as other normal queries.
It's my personal summary, if you have other questions or suggestions, welcome!