面试题答案
一键面试实现思路
- 确定搜索关键词:明确要突出显示片段的关键词。
- 使用高亮功能:Elasticsearch提供了高亮(Highlighting)机制,用于在搜索结果中突出显示匹配的文本片段。
API参数设置
在search
API中,通过highlight
参数来配置高亮功能:
{
"query": {
"match": {
"article_content_field": "your_keyword"
}
},
"highlight": {
"fields": {
"article_content_field": {}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"]
}
}
query
部分:使用match
查询在article_content_field
(文章内容字段)中搜索your_keyword
。highlight
部分:fields
:指定要高亮的字段,这里是article_content_field
。pre_tags
:指定高亮片段的前置标签,这里设置为<em>
,用于HTML强调。post_tags
:指定高亮片段的后置标签,这里设置为</em>
。
这样,搜索结果中的关键词所在片段就会被<em>
标签包围,实现突出显示。