1、引入配置
springboot环境
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
</parent>
引入es配置
<!--es-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、在service方法添加高亮代码
@Slf4j
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, PostEntity>
implements IPostService {
@Autowired
private ElasticSearchPostMapper elasticSearchPostMapper;
@Autowired
private ElasticsearchRestTemplate elasticsearchTemplate;
@Override
public List<PostIndex> searchInES(PostDto dto) {
//根据一个值查询多个字段 并高亮显示 这里的查询是取并集,即多个字段只需要有一个字段满足即可
//需要查询的字段
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
// .should(QueryBuilders.matchQuery("content", dto.getContent()))
.should(QueryBuilders.matchQuery("content", dto.getContent()));
//构建高亮查询
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQueryBuilder)
.withHighlightFields(
new HighlightBuilder.Field("content"))
.withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red'>").postTags("</span>"))
.build();
//查询
SearchHits<PostIndex> search = elasticsearchTemplate.search(searchQuery, PostIndex.class);
List<SearchHit<PostIndex>> searchHits = search.getSearchHits();
//设置一个最后需要返回的实体类集合
List<PostIndex> list = new ArrayList<>();
//遍历返回的内容进行处理
for (SearchHit<PostIndex> searchHit : searchHits) {
//高亮的内容
Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
//将高亮的内容填充到content中
searchHit.getContent().setContent(highlightFields.get("content") == null ? searchHit.getContent().getContent() : highlightFields.get("content").get(0));
// searchHit.getContent().setInfo(highlightFields.get("info") == null ? searchHit.getContent().getInfo() : highlightFields.get("info").get(0));
//放到实体类中
list.add(searchHit.getContent());
}
return list;
}
}
以上为作者在构建es高亮查询所总结的内容,如果有什么问题,欢迎在评论下方留言
标签:highlightFields,高亮,get,content,searchHit,elasticsearch,设置,getContent From: https://blog.51cto.com/u_14725510/7942856