ElasticSearch(es)使用游标读取全部数据

import com.cdel.utils.EsClientServiceFactoryByENV;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.Map;

public class bulkGetFaqAccV4 {
    private static Logger logger = LogManager.getLogger(bulkGetFaqAccV4.class);


    private static TransportClient client = EsClientServiceFactoryByENV.getInstance().getClient();


    public static void main(String[] args) {
        //数据来源索引
        String srcIndex = "xxx";
        String desType = "xxx";
 
 		//游标形式进行读取
        SearchResponse response = client.prepareSearch(srcIndex)//对应索引
                .setQuery(QueryBuilders.matchAllQuery()).setTypes(desType)//对应索引type
                .setScroll(TimeValue.timeValueMinutes(20))
                .setSize(1000).execute().actionGet();

        long totalHits = response.getHits().getTotalHits();
        logger.info("---------一共有{}个", totalHits);

        //
        while (response.getHits().getHits().length > 0) {
            BulkRequestBuilder bulkRequest = client.prepareBulk();

            SearchHits hits = response.getHits();
            SearchHit[] result = hits.getHits();
            for (SearchHit hit : result) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //TODO 具体处理逻辑
            }


            //获取下一批次的结果
            String scrollId = response.getScrollId();
            response = client.prepareSearchScroll(scrollId)
                    .setScroll(TimeValue.timeValueMinutes(20))//设置查询context的存活时间
                    .execute().actionGet();
        }

        //清理游标
        ClearScrollRequest request = new ClearScrollRequest();
        request.addScrollId(response.getScrollId());
        ClearScrollResponse clearScrollResponse = client.clearScroll(request).actionGet();


        client.close();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值