2017-04-21 86 views
0

我想通过使用java rest将json文档发送到elasticsearch。Java休息弹性搜索json文档

我只需要知道如何初始化变量“entities [i]”并将json文档放入其中。我尝试了很多方法,但仍然没有找到可行的东西。

这里是elastticsearch网站代码:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_example_requests.html

int numRequests = 10; 
final CountDownLatch latch = new CountDownLatch(numRequests); 

for (int i = 0; i < numRequests; i++) { 
    restClient.performRequestAsync(
     "PUT", 
     "/twitter/tweet/" + i, 
     Collections.<String, String>emptyMap(), 
     //assume that the documents are stored in an entities array 
     entities[i], 
     new ResponseListener() { 
      @Override 
      public void onSuccess(Response response) { 
       System.out.println(response); 
       latch.countDown(); 
      } 

      @Override 
      public void onFailure(Exception exception) { 
       latch.countDown(); 
      } 
     } 
    ); 
} 

//wait for all requests to be completed 
latch.await(); 

感谢您

+0

发布您尝试过的一些方法 –

回答

0
int numRequests = 1; 
    final CountDownLatch latch = new CountDownLatch(numRequests); 

    HttpEntity entity = new NStringEntity(
      "{\n" + 
        " \"user\" : \"kimchy\",\n" + 
        " \"post_date\" : \"2009-11-15T14:12:12\",\n" + 
        " \"message\" : \"trying out Elasticsearch\"\n" + 
        "}", ContentType.APPLICATION_JSON); 

    List<HttpEntity> entities = asList(entity); 

    for (int i = 0; i < numRequests; i++) { 
     restClient.performRequestAsync(
       "PUT", 
       "/twitter/tweet/" + i, 
       Collections.<String, String>emptyMap(), 
       entities.get(i), 
       new ResponseListener() { 
        @Override 
        public void onSuccess(Response response) { 
         System.out.println(response); 
         latch.countDown(); 
        } 

        @Override 
        public void onFailure(Exception exception) { 
         latch.countDown(); 
        } 
       } 
     ); 
    } 

    latch.await(); 

实体是一种HttpEntity.You需要在列表中创建HttpEntity对象的列表,并使用它们。

+0

我认为您发布的代码段会抛出ArrayIndexOutOfBoundException –

+0

现在就试试现在就试试。所以例子就是解释实体对象。 – Abhilash

+0

是的,谢谢它正在工作! – hugo