如何使用tags_schema为Elasticsearch查询词设置差异化高亮?
我之前也碰到过一模一样的需求,其实只要把查询结构和高亮配置结合起来调整就行,下面给你一步步拆解实现方法:
核心思路
Elasticsearch的tags_schema参数允许我们给高亮的<em>标签添加自定义类名,配合多条件查询,就能为不同关键词分配不同的样式标签。
具体实现步骤
1. 构造包含多关键词的查询
首先,我们需要把“foo”和“bar”拆成两个独立的查询条件,用bool.should包裹,这样Elasticsearch能分别识别不同的匹配项:
{ "query": { "bool": { "should": [ {"term": {"你的字段名": "foo"}}, {"term": {"你的字段名": "bar"}} ], "minimum_should_match": 1 } } }
2. 配置高亮规则,指定差异化标签
在highlight部分开启tags_schema: "styled",然后通过pre_tags和post_tags数组,为每个关键词对应设置带自定义类的标签:
{ "query": { "bool": { "should": [ {"term": {"content": "foo"}}, {"term": {"content": "bar"}} ], "minimum_should_match": 1 } }, "highlight": { "fields": { "content": { "tags_schema": "styled", "pre_tags": [ "<em class='foo-highlight'>", "<em class='bar-highlight'>" ], "post_tags": [ "</em>", "</em>" ] } } } }
3. 前端CSS定义样式
最后在前端页面中,针对自定义类名写CSS样式,就能看到不同的高亮效果了:
.foo-highlight { background: #ffeb3b; padding: 2px 4px; border-radius: 2px; } .bar-highlight { background: #2196f3; color: white; padding: 2px 4px; border-radius: 2px; }
关键说明
pre_tags和post_tags的顺序要和bool.should里的查询条件顺序对应,第一个条件匹配到的内容会用第一个标签,第二个条件用第二个标签。- 如果有更多关键词,只需要在
should里添加新的term,同时在pre_tags和post_tags里补充对应的标签即可。 - 如果你希望部分关键词共用同一种样式,只需要在
pre_tags里重复相同的标签字符串就行。
内容的提问来源于stack exchange,提问作者Hugh
相关产品推荐
相关产品推荐

