`//1. 构架一个原生查询器
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
//2.source 过滤
//2.1 参数:final String[] includes, final String[] excludes
// 如果不想执行 source 过滤能够将该行正文
queryBuilder.withSourceFilter(new FetchSourceFilter(strings,null));
//3. 查问条件
queryBuilder.withQuery(QueryBuilders.matchQuery(“name”,name));
//4. 设置分页和排序规定
queryBuilder
.withPageable(PageRequest.of(page,5, Sort.by(Sort.Direction.ASC,"price")));
//5. 高亮
HighlightBuilder.Field field = new HighlightBuilder.Field(“name”);
field.preTags(“<font style=’color:red’>”);
field.postTags(“</font>”);
queryBuilder.withHighlightFields(field);
//7. 查问
AggregatedPage<Product> result = elasticsearchTemplate.queryForPage(queryBuilder.build(), Product.class,new EsResultMapper());
List<Product> content = result.getContent();
content.stream().forEach(product -> System.out.println(product));`
`public class EsResultMapper implements SearchResultMapper {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
// 取得总记录数
long totalHits = response.getHits().getTotalHits();
// 记录列表
List<T> list = new ArrayList<>();
// 获取原始的搜寻后果
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
if (hits.getHits().length <= 0) {return null;
}
// 获取_source 属性中的所有数据
Map<String, Object> map = hit.getSourceAsMap();
// 取得高亮的字段
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
// 每个高亮字段都须要进行设置
for(Map.Entry<String,HighlightField> highlightField : highlightFields.entrySet()){
// 取得高亮的 key:高亮字段
String key = highlightField.getKey();
// 取得 value:高亮之后的成果
HighlightField value = highlightField.getValue();
// 将高亮字段和文本成果放入到 map 中
map.put(key,value.getFragments()[0].toString());
}
// 将 map 转换为对象
Gson gson = new Gson();
//map–>jsonString–> 对象
T t = gson.fromJson(gson.toJson(map), clazz);
list.add(t);
}
return new AggregatedPageImpl<>(list,pageable,totalHits);
}
}~~~~`