Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch 1.3. - Call custom REST endpoint from Java

I am currently building an elasticsearch plugin which exposes a REST endpoint ( starting from this post )

I can call my endpoint with curl like this :

curl -X POST 'http://my-es:9200/lt-dev_terminology_v1/english/_terminology?pretty=-d '{ 
   "segment": "database", 
   "analyzer": "en_analyzer"
}

My question is how can I call the same endpoint from java, using a transport client ? Could you point me to some tutorial ?

like image 978
Alexandra Avatar asked Nov 10 '22 07:11

Alexandra


1 Answers

I suggest that you take a look here. It should be a good starting point for you.

Let me sum up :

Considering the following parameters :

String clustername = "...";
String clientTransportHost = "...";
Integer clientTransportPort= "...";
String clientIndex = "...";
String indexType = "...";

Of course you replace the dots with the settings you wish to use.

Then you define your cluster Settings:

Settings settings = ImmutableSettings.settingsBuilder()
        .put("cluster.name", clustername).build();

You instantiate the TransportClient object :

    TransportClient client =  new TransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(clientTransportHost, clientTransportPort));

You can verify your connection using this method :

private void verifyConnection(TransportClient client) {
    ImmutableList<DiscoveryNode> nodes = client.connectedNodes();
    if (nodes.isEmpty()) {
        throw new ElasticsearchException(
                "No nodes available. Verify ES is running!");
    } else {
        log.info("connected to nodes: " + nodes.toString());
    }
}   

PS: to use the log.info() method you have to instantiate a Logger.

So now you can use the verification method :

verifyConnection(client);

and once you've done all that you can now per example prepare a search :

SearchResponse response = client.prepareSearch(clientIndex)
            .setTypes(indexType)
                            .addFields("...", "...")
            .setSearchType(SearchType.DEFAULT)
                            .execute()
                            .actionGet();

PS : Tested on Elasticsearch 1.3

like image 94
4 revs Avatar answered Nov 15 '22 07:11

4 revs