- 简介
- 查询语法
- 源码分析
简介
高亮显示是在结果文档中显示查询中的哪个或哪些单词被匹配的过程。
Elasticsearch底层使用Apache Lucene。 Lucene提供了三种类型的高亮实现:
第一种是标准类型(本文例子);第二种叫FastVectorHighlighter,
它需要词向量和位置才能工作;第三种叫PostingsHighlighter。
Elasticsearch自动选择正确的高亮实现方式:如果字段的配置中,
term_vector属性设成了with_positions_offsets,则将使用FastVectorHighlighter。
使用词向量将导致索引变大,但高亮显示的执行需要更少的时间。此外,
对于存储了大量数据的字段来说,推荐使用FastVectorHighlighter
查询语法
例如:高亮显示在title字段中匹配的单词,注意highlight部分和query部分位于JSON中的同一层,
也可以看做第一层。在Elasticsearch代码中,位于JSON第一层的query、highlight等叫做Element。
{
"query" : {
"term" : {
"title" : "crime"
}
},
"highlight" : {
"pre_tags" : [ "<b>" ],
"post_tags" : [ "</b>" ],
"fields" : {
"title" : {}
}
}
}
该查询的结果如下,结果中除标准返回信息外,还有一个highlight部分,
该部分使用<b>这个HTML标签来包含高亮部分,高亮由pre_tags和post_tags属性指定,
默认使用<em>标签。
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 0.19178301,
"hits" : [ {
"_index" : "library",
"_type" : "book",
"_id" : "4",
"_score" : 0.19178301,
{
"title": "Crime and Punishment",
"characters": ["Raskolnikov"],
"tags": [],
"copies": 0, "available" : true},
"highlight" : {
"title" : [ "**<b>Crime</b>** and Punishment" ]
}} ] }}
源码分析
'''(1)Elasticsearch code:注册fetchPhase中元素的解析方法'''
public class SearchService extends AbstractLifecycleComponent<SearchService> {
private final ImmutableMap<String, SearchParseElement> elementParsers;