2017-04-21 127 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