编码
/***
* @description: 多字段分词检索,条件过滤,分页,排序,高亮
* @return: void
**/
@Test
public void high() {
//高亮的字段
HighlightBuilder.Field nameField = new HighlightBuilder.Field("name").requireFieldMatch(false);//开启多字段同时高亮
nameField.preTags("<span style='color:red'>");
nameField.postTags("</span>");
//不建议使用 *
HighlightBuilder.Field contentField = new HighlightBuilder.Field("content").requireFieldMatch(false);//开启多字段同时高亮
contentField.preTags("<span style='color:red'>");
contentField.postTags("</span>");
//构建查询条件
NativeSearchQuery build = new NativeSearchQueryBuilder()
.withIndices("alibaba")//book 对象已有映射说明,可以不写
.withTypes("book")
.withQuery(QueryBuilders.queryStringQuery("这是").field("name").field("content"))//分词检索
.withFilter(QueryBuilders.rangeQuery("price").gt(8))//设置过滤条件
.withSort(new FieldSortBuilder("price").order(SortOrder.DESC))
.withPageable(PageRequest.of(0, 2))
.withHighlightFields(nameField, contentField)
.build();
//对查询结果进行高亮处理
AggregatedPage<Book> books = elasticsearchTemplate.queryForPage(build, Book.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
SearchHit[] hits = searchResponse.getHits().getHits();
List<Book> result = Lists.newArrayList();
for (SearchHit s :
hits) {
//获取原始数据
// System.out.println(s.getSourceAsString());
Map<String, Object> sourceAsMap = s.getSourceAsMap();
//获取高亮map
Map<String, HighlightField> highlightFields = s.getHighlightFields();
Book book = new Book();
book.setId(sourceAsMap.get("id").toString());
book.setName(sourceAsMap.get("name").toString());
//替换高亮字段
if (highlightFields.containsKey("name")) {
book.setName(highlightFields.get("name").fragments()[0].toString());
}
book.setAuthor(sourceAsMap.get("author").toString());
book.setContent(sourceAsMap.get("content").toString());
//替换高亮字段
if (highlightFields.containsKey("content")) {
book.setContent(highlightFields.get("content").fragments()[0].toString());
}
book.setPrice(new BigDecimal(sourceAsMap.get("id").toString()));
book.setPubDate(new Date(Long.valueOf(sourceAsMap.get("pubDate").toString())));
result.add(book);
}
return new AggregatedPageImpl<T>((List<T>) result);
}
});
//直接遍历出聚合查询的元素
books.forEach(a -> {
System.out.println(a);
});
}
测试
页面处理
v-html 进行解析
<p class="xxx">
<a v-html= "result.name" > </a>
</p>