天天看点

es sroll分页查询

public Map<String, Object> page(QueryEntity queryEntity) {

// // 1. 创建 ES 连接池

// JestClientFactory jestClientFactory = new JestClientFactory();

//

// // 2. 配置 ES 信息

// HttpClientConfig config = new HttpClientConfig.Builder(“http://127.0.0.1:9200”).build();

// jestClientFactory.setHttpClientConfig(config);

//

// // 3. 获取 ES 连接

// JestClient jestClient2 = jestClientFactory.getObject();

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

//全文搜索

if(StringUtils.isNotBlank(queryEntity.getKeyword())){

sourceBuilder.query(QueryBuilders.queryStringQuery(queryEntity.getKeyword()).analyzer(“ik_max_word”));

}

sourceBuilder.size(queryEntity.getPageSize());

//匹配度倒数,数值越大匹配度越高

sourceBuilder.sort(“_score”, SortOrder.DESC);

//时间倒序

sourceBuilder.sort(“updateTime”, SortOrder.DESC);

Search search = new Search.Builder(sourceBuilder.toString())

//索引名称

.addIndex(AppInfo.INDEX)

//游标过期时间1分钟

.setParameter(Parameters.SCROLL, “1m”)

//展示的字段

.setParameter(“filter_path”, “_scroll_id,hits.total.value,hits.hits”)

.build();

try {

JestResult jestResult = jestClient.execute(search);
        System.out.println("jestResult="+jestResult.getJsonString());

        String scrollId = jestResult.getJsonObject().get("_scroll_id").getAsString();
        long total = jestResult.getJsonObject().get("hits")
                .getAsJsonObject().get("total")
                .getAsJsonObject().get("value").getAsLong();

        //第一页数据已经获取到
        List<AppInfo> appList = jestResult.getSourceAsObjectList(AppInfo.class);
        //从第二页开始
        for (int i = 1; i < queryEntity.getPageNum(); i++) {
            appList = searchEventHistogramByScroll(AppInfo.class, scrollId);
        }

        //设置分页数据
        Map<String, Object> results = new HashMap<>();
        queryEntity.init(total);	//计算总页数
        results.put("pageNum", queryEntity.getPageNum());
        results.put("pageSize", queryEntity.getPageSize());
        results.put("total", total);
        results.put("pageCount", queryEntity.getPageCount());
        results.put("list", appList);
        return results;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}