web-dev-qa-db-fra.com

Pourquoi ne puis-je pas me connecter à ElasticSearch via une API Java?

Je ne parviens pas à me connecter au cluster Vanilla ElasticSearch via l'API Java.

Reproduire:

#start elasticsearch
elasticsearch -f

#checking in a new window
$ curl -XPUT 'http://localhost:9200/Twitter/Tweet/1' -d '{\
    "user" : "kimchy",\
    "post_date" : "2009-11-15T14:12:12",\
    "message" : "trying out Elastic Search"\
}'

résultat:

{
  "ok": true,
  "_index": "Twitter",
  "_type": "Tweet",
  "_id": "1",
  "_version": 3
}

$ curl -XGET 'http://localhost:9200/Twitter/Tweet/_search?q=user:kimchy'

résultat:

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.30685282,
    "hits": [
      {
        "_index": "Twitter",
        "_type": "Tweet",
        "_id": "1",
        "_score": 0.30685282,
        "_source": {
          "user": "kimchy",
          "post_date": "2009-11-15T14:12:12",
          "message": "trying out Elastic Search"
        }
      }
    ]
  }
}

Donc, tout fonctionne via HTTP. Essayer via Java (par cette page ):

public static void main(String[] args) {

    Client client = new TransportClient()
    .addTransportAddress(new InetSocketTransportAddress("localhost", 9200));

    IndexResponse response = null;
    try {
      response = client.prepareIndex("Twitter", "Tweet", "1")
          .setSource(XContentFactory.jsonBuilder()
                      .startObject()
                          .field("user", "john")
                          .field("postDate", new Date())
                          .field("message", "who dont it work")
                      .endObject()
                    )
          .execute()
          .actionGet();
    } catch (ElasticSearchException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    System.out.println(response);
}

Et je reçois la trace de pile suivante:

May 21, 2013 8:27:42 AM org.elasticsearch.plugins
INFO: [Bes] loaded [], sites []
May 21, 2013 8:27:49 AM org.elasticsearch.client.transport
INFO: [Bes] failed to get node info for [#transport#-1][inet[localhost/127.0.0.1:9200]], disconnecting...
org.elasticsearch.transport.ReceiveTimeoutTransportException: [][inet[localhost/127.0.0.1:9200]][cluster/nodes/info] request_id [0] timed out after [5002ms]
    at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.Java:342)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.Java:895)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:918)
    at Java.lang.Thread.run(Thread.Java:680)
Exception in thread "main" org.elasticsearch.client.transport.NoNodeAvailableException: No node available
    at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.Java:202)
    at org.elasticsearch.client.transport.support.InternalTransportClient.execute(InternalTransportClient.Java:106)
    at org.elasticsearch.client.support.AbstractClient.index(AbstractClient.Java:84)
    at org.elasticsearch.client.transport.TransportClient.index(TransportClient.Java:310)
    at org.elasticsearch.action.index.IndexRequestBuilder.doExecute(IndexRequestBuilder.Java:315)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.Java:62)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.Java:57)
    at Scratch.main(Scratch.Java:30)

Et la chose la plus proche que j'ai trouvée jusqu'à présent à ce problème est ici , mais le fil a traîné sans résolution.

25
JnBrymn

Le port par défaut de TransportClient est 9300. Vous devez l’utiliser au lieu de 9200 dans votre code Java. C'est probablement pourquoi la connexion a échoué.

70
mguillermin
import Java.net.InetAddress;
import Java.net.UnknownHostException;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;


public class ElasticsearchTest {  
    public static void main(String[] argv) throws UnknownHostException{ 

        /* //Set new cluester
        Settings settings = Settings.builder()
                .put("cluster.name", "newCluster")
                .put("node.name","newNode").build();*/

        //create cliet !!!Make sure keep settings empty if your cluster is the 
        //same as the one you defined in your elasticsearch.yml file
        //Plus, port here(9300)must be different from your http port(9200)

        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //get data
        GetResponse response = client.prepareGet("Twitter", "Tweet", "1").execute().actionGet();

       //output
        System.out.println(response.getSourceAsString());

        client.close(); 
        } 
    } 
0
Eli Zheng