elasticsearch 5.x highlight 高亮

public static Map search(String key,String index,String type,int start,int row){

//创建查询索引,要查询的索引库为index
SearchRequestBuilder builder = getClient().prepareSearch(index);
builder.setTypes(type);
builder.setFrom(start);
builder.setSize(row);

//设置查询类型:1.SearchType.DFS_QUERY_THEN_FETCH 精确查询; 2.SearchType.SCAN 扫描查询,无序
builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
if(StringUtils.isNotBlank(key)){
// 设置查询关键词
builder.setQuery(QueryBuilders.multiMatchQuery(key, "title","describe"));
}

//设置是否按查询匹配度排序

builder.setExplain(true);

//设置高亮显示
HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
highlightBuilder.preTags("");
highlightBuilder.postTags("
");
builder.highlighter(highlightBuilder);


//执行搜索,返回搜索响应信息
SearchResponse searchResponse = builder.get();
SearchHits searchHits = searchResponse.getHits();

//总命中数
long total = searchHits.getTotalHits();
Map map = new HashMap();
SearchHit[] hits = searchHits.getHits();
map.put("count", total);
List> list = new ArrayList>();
for (SearchHit hit : hits) {
//highlightFields.size=0??
Map highlightFields = hit.getHighlightFields();

//title高亮
HighlightField titleField = highlightFields.get("title");
Map source = hit.getSource();
if(titleField!=null){
Text[] fragments = titleField.fragments();
String name = "";
for (Text text : fragments) {
name+=text;
}
source.put("title", name);
}

//describe高亮
HighlightField describeField = highlightFields.get("describe");
if(describeField!=null){
Text[] fragments = describeField.fragments();
String describe = "";
for (Text text : fragments) {
describe+=text;
}
source.put("describe", describe);
}
list.add(source);
}
map.put("dataList", list);
return map;
}

你可能感兴趣的:(Elasticsearch,6.x,学习笔记)