SpringBoot+elastisearch7.9高亮搜索信息
Pageable pageable = PageRequest.of(pageNum, pageSize);
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "filetype","fileName","attachment.content_type"}, null));
nativeSearchQueryBuilder.withPageable(pageable);
if (StringUtils.isEmpty(keyword)) {
nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
} else {
HighlightBuilder.Field field = new HighlightBuilder.Field("fileName").preTags("<font style='color:red'>").postTags("</font>");
nativeSearchQueryBuilder.withHighlightFields(field);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(QueryBuilders.matchQuery("fileName", keyword));
boolQueryBuilder.should(QueryBuilders.matchQuery("attachment.content", keyword));
nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
}
nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
SearchHits<FileWord> kilst=elasticsearchRestTemplate.search(searchQuery, FileWord.class);
List<FileWord> filewordlist=new ArrayList<FileWord>();
kilst.forEach(item -> {
FileWord content = item.getContent();
List<String> filename=item.getHighlightField("fileName");
if(filename.size()>0) {
content.setFileName(filename.get(0));
}
filewordlist.add(content);
});
Page<FileWord> pagelist = new PageImpl<>(filewordlist,pageable,kilst.getTotalHits());
return pagelist;