其他分享
首页 > 其他分享> > ElasticSearch高级用法之滚动查询

ElasticSearch高级用法之滚动查询

作者:互联网

由于es的限制,普通查询最多查询10000条数据,那么需要查询数据量大的情况怎么办呢?这个时候就可以使用滚动查询。代码如下:

 //设置查询超时时间
        Scroll scroll = new Scroll(TimeValue.timeValueMillis(5L));
        //滚动查询
        searchRequest.scroll(scroll);
        //记录要滚动的id
        String scrollId = searchResponse.getScrollId();
        //滚动查询部分,将从第1001笔数据开始取
        SearchHit[] hitsScroll = hits.getHits();
        while (hitsScroll != null && hitsScroll.length > 0) {
            //构造滚动查询条件
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            scrollRequest.scroll(scroll);
            try {
                searchResponse = client.restHighLevelClient().scroll(scrollRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            scrollId = searchResponse.getScrollId();
            System.out.println(scrollId);
            hits = searchResponse.getHits();
            hitsScroll = hits.getHits();
            //对结果进行操作
            for (SearchHit hit : hits) {
                CntdDataDeliver cntdDataDeliver=JSON.parseObject(hit.getSourceAsString(), CntdDataDeliver.class);
                list.add(cntdDataDeliver);
            }
        }
        //清除滚动
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);
        try {
            client.restHighLevelClient().clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

标签:滚动,查询,hitsScroll,ElasticSearch,searchResponse,scrollId,用法,scroll
来源: https://www.cnblogs.com/Johnson8888/p/16630968.html