Hello,World

怎么做到像百度搜索高亮内容预览

匿名 | 发布于2019年10月06日 | 阅读数:2599


]S1SHC]UKM7QZP~Q}32F7)7.png

如图所示在高亮标题下面,对高亮内容可以预览
已邀请:

doom

赞同来自: EricTowns

        SearchRequestBuilder builder = getClient().prepareSearch(index);
builder.setTypes(type);
builder.setFrom(start);
builder.setSize(row);

//设置高亮显示,字体设置为红色
HighlightBuilder highlightBuilder = new HighlightBuilder().field("title").field("describe").requireFieldMatch(false);
highlightBuilder.preTags("<span style=\"color:red\">");
highlightBuilder.postTags("</span>");
builder.highlighter(highlightBuilder);

builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);

这是查询的时候添加;
		builder.setExplain(true);
SearchResponse searchResponse = builder.get();

SearchHits hits = searchResponse.getHits();
long total = hits.getTotalHits();
Map<String, Object> map = new HashMap<String,Object>();
SearchHit[] hits2 = hits.getHits();
map.put("count", total);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (SearchHit searchHit : hits2) {
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightField = highlightFields.get("title");
Map<String, Object> source = searchHit.getSourceAsMap();
if(highlightField!=null){
Text[] fragments = highlightField.fragments();
String name = "";
for (Text text : fragments) {
name+=text;
}
source.put("title", name);
}
HighlightField highlightField2 = highlightFields.get("describe");
if(highlightField2!=null){
Text[] fragments = highlightField2.fragments();
String describe = "";
for (Text text : fragments) {
describe+=text;
}
source.put("describe", describe);
}
list.add(source);
}
map.put("dataList", list);
return map;
这是获取高亮的结果

 

doom

赞同来自:

有高亮的语法

God_lockin

赞同来自:

我们之前高亮是这样实现的
1.  query的文字部分拆出来单独过分词器做分词(跟title、content字段同款分词器)
2. 完整的query丢ES里做召回
3. 把文档的结果连同分词结果一起返回前端
4. 前端根据分词结果对文章/标题进行高亮

要回复问题请先登录注册