使用TransportCilent的Java ElasticSearch示例

时间:2014-04-24 06:53:22

标签: java json elasticsearch

以下代码解释了Java和ElasticSearch之间的通信 使用传输客户端。当我运行时,我得到org.elasticsearch.nodedisconnectedException。任何明确的Java Elasticsearch示例都将受到赞赏,或者任何人都可以帮助我找到解决方案。

public static Client function() {
    Settings setting = ImmutableSettings.settingsBuilder().put("cluster.name", "localtestsearch").build();
    client = new TransportClient();
    client = client.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
    return client;

}

public static void main(String[] args) {

    System.out.println("In Main Method");

    try {
        System.out.println("In try block");
        Client client = new TransportClient()
                .addTransportAddress(new InetSocketTransportAddress("localhost",
                        9300));


        System.out.println("Connected");

        client.close();

        Settings settings = ImmutableSettings.settingsBuilder()
                .put("client.transport.sniff", true).build();
        TransportClient client1 = new TransportClient(settings);


        org.elasticsearch.node.Node node = nodeBuilder().node();
        System.out.println("Node " + node);

        Client client = node.client();

        System.out.println("calling Client from Node " + client);

        node.close();
        System.out.println("Node CLosed");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

}

1 个答案:

答案 0 :(得分:2)

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class Test {
   public static void main(String[] args) {
       TransportClient client = new TransportClient();

       for(String host: client.settings().getAsArray("transport.client.initial_nodes")) {
           int port = 9300;

          // or parse it from the host string...
           String[] splitHost = host.split(":", 2);
           if(splitHost.length == 2) {
               host = splitHost[0];
               port = Integer.parseInt(splitHost[1]);
           }

           client.addTransportAddress(new InetSocketTransportAddress(host, port));
       }

       // ...
   }
}