1. Settings settings = Settings.builder()
    2. .put("cluster.name", "myClusterName").build();
    3. TransportClient client = new PreBuiltTransportClient(settings);
    4. client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    5. //Add transport addresses and do something with the client...
    6. //client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), nodePort));
    1. //
    2. BulkRequestBuilder bulkRequest = client.prepareBulk();
    3. bulkRequest.add(client.prepareIndex("index1", "type1", "id1").setSource(source);
    4. bulkRequest.add(client.prepareIndex("index2", "type2", "id2").setSource(source);
    5. BulkResponse bulkResponse = bulkRequest.execute().actionGet();

    BulkRequestBuilder?

    1. 允许批量提交indexdelete请求

    实现往ES中添加数据

    1. public static void putEsIndex() {
    2. Settings settings = ImmutableSettings.settingsBuilder()
    3. .put("cluster.name", "elasticsearch").build();
    4. TransportClient client = null;
    5. client = new TransportClient(settings);
    6. try {
    7. client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.253"), 9300));
    8. } catch (UnknownHostException e) {
    9. e.printStackTrace();
    10. }
    11. final BulkRequestBuilder bulkRequest = client.prepareBulk();
    12. Map<String, Object> map = new HashMap<>();
    13. map.put("filename", "Z_SURF_I_A5703_20170101000000_O_AWS_DAY.txt");
    14. bulkRequest.add(client.prepareIndex("qx_file",
    15. "qx_file",
    16. "20170101/Z_SURF_I_A5703_20170101000000_O_AWS_DAY.txt").setSource(map));
    17. bulkRequest.execute().actionGet();
    18. }

    实现读取ES的数据

    1. public static void Search() {
    2. Settings settings = ImmutableSettings.settingsBuilder()
    3. .put("cluster.name", "elasticsearch").build();
    4. TransportClient client = null;
    5. client = new TransportClient(settings);
    6. try {
    7. client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.1.253"), 9300));
    8. } catch (UnknownHostException e) {
    9. e.printStackTrace();
    10. }
    11. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    12. boolQueryBuilder.must(QueryBuilders.termsQuery("filename", "20170101000000"));
    13. SearchRequestBuilder searchRequestBuilder = null;
    14. searchRequestBuilder = client.prepareSearch("qx_file").setTypes("qx_file").setSearchType(SearchType.QUERY_THEN_FETCH);
    15. // searchRequestBuilder.setQuery(qb);
    16. // searchRequestBuilder.setFrom(0);
    17. // searchRequestBuilder.setSize(size);
    18. // searchRequestBuilder.addSort(sortBuilder);
    19. SearchResponse searchRespons = searchRequestBuilder.execute().actionGet();
    20. SearchHit[] hitArray = searchRespons.getHits().getHits();
    21. for( int i = 0; i < hitArray.length; i++) {
    22. System.out.println(hitArray[i].id());
    23. }
    24. }