ES - Elasticsearch分页查询

话不多说,直接上货

public void search() throws Exception {

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

    // 构建查询条件(boolQuery:多条件查询)
    String query = searchSourceBuilder.query(QueryBuilders.boolQuery()
                    .must(QueryBuilders
                            .matchPhraseQuery("ecs.version", "1.1.0")) // 短词匹配
            /*.must(QueryBuilders
                    .matchPhraseQuery("time",new Date() )) // 查询时间匹配*/
    )
            .fetchSource("message", null) // 查询结果只获取message字段,排除其它字段
            .toString();
            
    System.out.println("构建查询DSL语句:" + query);

    // 构建查询对象
    Search search = new Search.Builder(query)
            .setParameter(Parameters.SIZE, 1000) //每次获取的数量
            .setParameter(Parameters.SCROLL, "5m") //游标有效时间
            .build();

    JestResult jestResult = jestClient.execute(search);
    // 获取查询关键字总量
    int hitCount = getHitCount(jestResult);
    System.out.println("获取到关键字数量为:" + hitCount);
    // 获取结果
    List<JSONObject> objectList = jestResult.getSourceAsObjectList(JSONObject.class);

    //获取游标
    String scrollId = jestResult.getJsonObject().get("_scroll_id").getAsString();
    // 第一次根据游标获取,之后循环
    jestResult = searchEventHistogramByScroll(scrollId);
    while (jestResult.isSucceeded() && jestResult.getSourceAsObjectList(JSONObject.class).size() > 0) {
        // 根据游标分页获取数据
        List<JSONObject> results = jestResult.getSourceAsObjectList(JSONObject.class);
        // 游标其实每次获取的都相同,可以省去这一步
        // scrollId = jestResult.getJsonObject().get("_scroll_id").getAsString();
        // 根据游标循环查询
        jestResult = searchEventHistogramByScroll(scrollId);
    }
}
    /**
     * @param result
     * @Description: 获取匹配到的数量
     * @author: lhw
     * @date: 2020/12/19 12:24
     * @Return: int
     */
private int getHitCount(JestResult result) {
    return result.getJsonObject().get("hits").getAsJsonObject().get("total").getAsJsonObject().get("value").getAsInt();
}
/**
 * @param scrollId
 * @Description: 根据游标循环获取数据
 * @author: lhw
 * @date: 2020/12/19 12:02
 * @Return: io.searchbox.client.JestResult
 */
public JestResult searchEventHistogramByScroll(String scrollId) throws ServerException {

    SearchScroll scroll = new SearchScroll.Builder(scrollId, "5m").build();
    JestResult result = null;
    try {
        result = jestClient.execute(scroll);
    } catch (IOException e) {
        logger.error("根据游标循环获取数据异常,异常原因:{}", e.toString());
        throw new ServerException("根据游标循环获取数据异常", e);
    }

    return result;
}

ES配置在另一篇文章戳我

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值