9-2 es kafka

image.png
image.png
image.png
image.png
image.png
`//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("");
field.postTags("
");
queryBuilder.withHighlightFields(field);
//7.查询
AggregatedPage result = elasticsearchTemplate.queryForPage(queryBuilder.build(), Product.class,new EsResultMapper());
List content = result.getContent();
content.stream().forEach(product -> System.out.println(product));`

`public class EsResultMapper implements SearchResultMapper {

@Override

public AggregatedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) {

    //获得总记录数

long totalHits = response.getHits().getTotalHits();
//记录列表
List list = new ArrayList<>();
//获取原始的搜索结果
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {

        if (hits.getHits().length <= 0) {
            return null;

}

        //获取_source属性中的所有数据

Map map = hit.getSourceAsMap();
//获得高亮的字段
Map highlightFields = hit.getHighlightFields();
//每个高亮字段都需要进行设置
for(Map.Entry 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);

}
}~~~~`

image.png

image.png
image.png

你可能感兴趣的:(9-2 es kafka)