編碼
/***
* @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) {
//獲取原始數(shù)據(jù)
// 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>