ElasticSearch scroll查询 api
1、scroll深度搜索,查询符合条件的所有数据。如果不是scroll深度搜索默认之后返回20条数据,如果指定分页就返回分页的条数。
package com.example.demo; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.transport.client.PreBuiltTransportClient; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Map; public class TestDemo { @Autowired PreBuiltTransportClient preBuiltTransportClient; /** * 查询所有数据 * @param indices * @param type * @param queryBuilder * @param pageSize * @return */ public List<Map<String,Object>> searchAllData(String indices, String type, QueryBuilder queryBuilder, Integer pageSize){ List result = new ArrayList<>(); List tmpList = new ArrayList<>(); SearchResponse scrollResp = preBuiltTransportClient.prepareSearch(indices) .setTypes(type) .setScroll(new TimeValue(60000)) .setQuery(queryBuilder) .setSize(pageSize).get(); do { for (SearchHit hit : scrollResp.getHits().getHits()) { tmpList.add(hit.getSourceAsMap()); } result.addAll(tmpList); tmpList.clear(); scrollResp = preBuiltTransportClient.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet(); } while (scrollResp.getHits().getHits().length != 0); return result; } /** * 查询职位是经理而且工资1万元以上的员工,然后计算他们的年终奖金 * @param index * @param type */ public void calculateBonus(String index,String type){ try{ Integer pageSize = 100; BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //查询条件1: 工资是1万元以上 boolQueryBuilder.must(QueryBuilders.rangeQuery("salary").gt(10000)); //查询条件2:职位是经理级别 boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("level","经理")); List<Map<String, Object>> dataList = this.searchAllData(index, type, boolQueryBuilder, pageSize); if(dataList != null){ for(Map<String, Object> data : dataList){ //业务逻辑处理,例如:计算年终奖金 } } }catch (Exception e){ e.printStackTrace(); } } }
感谢您的阅读,您的支持是我写博客动力。