ElastichSearch通过配置highlight字段可以实现高亮查询,通过fields指定需要搞定的字段,返回结果中需要高亮的词默认使用html标签em包裹,em标签主要起强调作用,我们可以自定义用什么样的css标签来进行包裹
POST /test/_search
{
"query": {
"match": {
"desc": "芒"
}
},
"highlight": {
"fields": {
"desc": {}
}
}
}
返回结果:
{
"took" : 87,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.6931471,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "JASwgHQByM5jgHs7lImo",
"_score" : 0.6931471,
"_source" : {
"name" : "奥黛丽·赫本",
"desc" : "光芒四射"
},
"highlight" : {
"desc" : [
"光<em>芒</em>四射"
]
}
}
]
}
}
自定义高亮标签
POST /test/_search
{
"query": {
"match": {
"desc": "芒"
}
},
"highlight": {
"fields": {
"desc": {}
},
# 标签前缀
"pre_tags":"<font color='red'>",
# 标签后缀
"post_tags": "</font>"
}
}
返回结果:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.6931471,
"hits" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "JASwgHQByM5jgHs7lImo",
"_score" : 0.6931471,
"_source" : {
"name" : "奥黛丽·赫本",
"desc" : "光芒四射"
},
"highlight" : {
"desc" : [
"光<font color='red'>芒</font>四射"
]
}
}
]
}
}