从索引库中将检索到的数据导出到外部文件,文件格式为.json
1 package com.juyun.test; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.net.InetAddress; 8 import java.net.UnknownHostException; 9 10 import org.elasticsearch.action.search.SearchResponse; 11 import org.elasticsearch.client.transport.TransportClient; 12 import org.elasticsearch.common.settings.Settings; 13 import org.elasticsearch.common.transport.InetSocketTransportAddress; 14 import org.elasticsearch.index.query.QueryBuilder; 15 import org.elasticsearch.index.query.QueryBuilders; 16 import org.elasticsearch.search.SearchHits; 17 import org.elasticsearch.transport.client.PreBuiltTransportClient; 18 19 public class ElasticsearchBulkOut { 20 21 /** 22 * 把索引库中的文档以json格式批量导出到文件中 23 * @param args 24 */ 25 public static void main(String[] args) { 26 27 try { 28 // 设置集群名称 29 Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build(); 30 // 创建client 31 TransportClient client = new PreBuiltTransportClient(settings) 32 .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("172.16.0.157"), 9300)); 33 34 SearchResponse response = client.prepareSearch("flow") 35 .setTypes("data") 36 .setSize(5000) 37 .setQuery(QueryBuilders.matchAllQuery()) 38 .execute().actionGet(); 39 SearchHits resultHits = response.getHits(); 40 41 File article = new File("C:/Users/juyun/Desktop/data.json"); 42 FileWriter fw = new FileWriter(article); 43 BufferedWriter bfw = new BufferedWriter(fw); 44 45 if (resultHits.getHits().length == 0) { 46 System.out.println("查到0条数据!"); 47 48 } else { 49 for (int i = 0; i < resultHits.getHits().length; i++) { 50 String jsonStr = resultHits.getHits()[i] 51 .getSourceAsString(); 52 System.out.println(jsonStr); 53 bfw.write(jsonStr); 54 bfw.write("\n"); 55 } 56 } 57 bfw.close(); 58 fw.close(); 59 60 } catch (UnknownHostException e) { 61 e.printStackTrace(); 62 } catch (IOException e) { 63 e.printStackTrace(); 64 } 65 } 66 67 }
ElasticSearchBulkOut
时间: 2024-10-27 12:16:32