最近工作中看到一段Springboot整合ES高亮效果的代码,时间不多就大致看一会,休息时间凭借记忆写出来,但是效果出不来,有没有熟悉高亮的友人帮忙看看哪里错了。
springboot用的2.7.0,es data4.4.0,es7.17.3的
代码如下
@Resource
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public Map searchWC(Integer page, Integer limit, String kw) {
Pageable pageable = PageRequest.of(page - 1, limit);
NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
searchQueryBuilder.withPageable(pageable);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (kw!=null && "".equals(kw)){
boolQueryBuilder.should(QueryBuilders.multiMatchQuery(kw, "name", "age"));
}
searchQueryBuilder.withFilter(boolQueryBuilder);
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder).scoreMode(FunctionScoreQuery.ScoreMode.SUM).setMinScore(1);
searchQueryBuilder.withQuery(functionScoreQueryBuilder);
// 配置高亮
HighlightBuilder highlighter = new HighlightBuilder();
highlighter.field("name");
highlighter.field("age");
highlighter.preTags("<font color='red'>");
highlighter.postTags("</font>");
searchQueryBuilder.withHighlightBuilder(highlighter);
NativeSearchQuery searchQuery = searchQueryBuilder.build();
// 查询
SearchHits<User> searchHits = elasticsearchRestTemplate.search(searchQuery, User.class);
if(searchHits.getTotalHits()<=0){
return null;
}
// 处理结果
List list = new ArrayList();
Map searchResultMap = new HashMap<>();
List<SearchHit<User>> result = searchHits.getSearchHits();
result.forEach(r -> {
//原始数据
User user = r.getContent();
//高亮数据
Map<String, List<String>> highlightFields = r.getHighlightFields();
//处理name字段
List<String> names = highlightFields.get("name");
if (names != null && names.size() > 0) {
StringBuffer buffer = new StringBuffer();
for (String s : names) {
buffer.append(s);
System.out.println(s);
}
user.setName(buffer.toString());
}
//处理age字段
List<String> ages = highlightFields.get("age");
if (ages != null && ages.size() > 0) {
StringBuffer buffer = new StringBuffer();
for (String s : ages) {
buffer.append(s);
System.out.println(s);
}
user.setAge(Integer.parseInt(buffer.toString()));
}
//=============没数据???================
if(names==null){
System.out.println("names无数据");
}
if(ages==null){
System.out.println("ages无数据");
}
list.add(user);
});
searchResultMap.put("dataList",list);
//保存分页信息:总条数total、总页数pages、结果当前页currPage
long hitsTotalValue = searchHits.getTotalHits();
searchResultMap.put("total", hitsTotalValue);
searchResultMap.put("pages", (long) Math.ceil(hitsTotalValue / limit));
searchResultMap.put("currPage", page);
return searchResultMap;
}
现在的状况是,请求发出后,返回的结果中是整个users索引库中的所有测试数据,就是没有高亮和过滤的效果,分页没问题