elasticsearch遍歷出全部資料
阿新 • • 發佈:2019-02-14
@Test public void testScroll() throws IOException { TransportClient esClient = new ESClient().getInstance(); SearchResponse searchResponse = esClient.prepareSearch(indexName) .setTypes(type) .setSize(10000) //這個遊標維持多長時間 .setScroll(TimeValue.timeValueMinutes(8)) .execute().actionGet(); System.out.println(searchResponse.getHits().getTotalHits()); StringBuffer buffer = new StringBuffer(); while(true){ for (SearchHit hit : searchResponse.getHits()) { System.out.println(hit.getSourceAsString()); buffer.append(hit.getSourceAsString().replace("\n"," ")+"\n"); } searchResponse = esClient.prepareSearchScroll(searchResponse.getScrollId()) .setScroll(TimeValue.timeValueMinutes(8)) .execute().actionGet(); if (searchResponse.getHits().getHits().length == 0) { break; } } FileOutputStream out = newFileOutputStream("E:/tmp/scrolldata.es"); out.write(buffer.toString().getBytes()); out.close(); System.out.println("檔案寫入成功"+"E:/tmp/scrolldata.es"); }