本文主要使用spring-data-elasticsearch 对es进行操作。并且是前后端分离的项目,所以实现搜索结果的匹配字段的高亮显示有两种方式,
一个是后端,一个是前端:
项目完整源码地址:https://github.com/Dr-Water/springdata-es-action
后端实现高亮显示
1、定义HighlightResultMapper
/** *@业务描述: 用于对es搜索结果再加工 */ public class HighlightResultMapper implements SearchResultMapper { @Override public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> clazz, Pageable pageable) { long totalHits = searchResponse.getHits().getTotalHits(); List<T> list = new ArrayList<>(); SearchHits hits = searchResponse.getHits(); if (hits.getHits().length> 0) { for (SearchHit searchHit : hits) { Map<String, HighlightField> highlightFields = searchHit.getHighlightFields(); T item = JSON.parseObject(searchHit.getSourceAsString(), clazz); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (highlightFields.containsKey(field.getName())) { try { field.set(item, highlightFields.get(field.getName()).fragments()[0].toString()); } catch (IllegalAccessException e) { e.printStackTrace(); } } } list.add(item); } } return new AggregatedPageImpl<>(list, pageable, totalHits); } @Override public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) { return null; }
2、 对Controller代码进行编写
/** * 高亮显示 * @param keyword * @param pageNum * @param pageSize * @return */ @GetMapping("/getUserList") public Page<User> query2( String keyword, Integer pageNum, Integer pageSize) { if(pageNum == null || pageNum <= 0){ pageNum = 1; } if(pageSize == null || pageSize <= 0){ pageSize = 5; } String preTags = "<span style=\"color:#F56C6C\">"; String postTags = "</span>"; HighlightBuilder.Field firstName = new HighlightBuilder.Field("firstName").preTags(preTags).postTags(postTags); HighlightBuilder.Field lastName = new HighlightBuilder.Field("lastName").preTags(preTags).postTags(postTags); HighlightBuilder.Field[] fields =new HighlightBuilder.Field[2]; fields[0]= firstName; fields[1]= lastName; SearchQuery searchQuery = null; if (!StringUtils.isEmpty(keyword)) { searchQuery = new NativeSearchQueryBuilder() .withPageable(PageRequest.of(pageNum - 1, pageSize)) .withQuery(QueryBuilders.multiMatchQuery(keyword, "firstName", "lastName")) .withHighlightFields(fields) .withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC)) .build(); } else { searchQuery = new NativeSearchQueryBuilder() .withPageable(PageRequest.of(pageNum - 1, pageSize)) .withQuery(QueryBuilders.matchAllQuery()) .withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC)) .build(); } Page<User> users = estemplate.queryForPage(searchQuery, User.class, new HighlightResultMapper()); return users; }
返回结果如下:前端把结果进行解析即可实现高亮