简体   繁体   中英

How to connect to ElasticSearch with Java transport client?

I am following the ElasticSearch documentation on Java Client. I have started ElasticSearch and I can interact with it with the Rest API. I want to use the Java Client and so far I have a main like this:

public class TestElastic {

public static void main(String[] args) {
    try{
        TransportClient client = TransportClient.builder().build()
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        JSONObject place = new JSONObject();
        place.put("name", "AAAAA");
        IndexResponse response = client.prepareIndex("my_database", "places", "1")
                .setSource(place)
                .get();
        System.out.println(response.toString());
        // Index name
        String _index = response.getIndex();
        System.out.println(_index);
        // Type name
        String _type = response.getType();
        System.out.println(_type);
        // Document ID (generated or not)
        String _id = response.getId();
        System.out.println(_id);
        // Version (if it's the first time you index this document, you will get: 1)
        long _version = response.getVersion();
        System.out.println(_version);
        // isCreated() is true if the document is a new one, false if it has been updated
        boolean created = response.isCreated();
        System.out.println(created);
        client.close();
    }catch (Exception ex){
        ex.printStackTrace();
    }
}

}

In the Java logs I can see that there is a connection with 127.0.0.1:9300. But after the "prepare index" command I do not see any error and nothing is printed(I have some system out commands). In the ElasticSearch logs is also nothing relative. When I create an index with the Rest API I can see this in the logs.

Ok, as @Val mentioned I forgot to print the errors. The problem was that JSONObject is not the format that ElasticSearch wants. Map and HashMap are acceptable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM