Example requestsedit

Here are a couple of examples:

Response response = restClient.performRequest("GET", "/",
        Collections.singletonMap("pretty", "true"));
System.out.println(EntityUtils.toString(response.getEntity()));

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

Response indexResponse = restClient.performRequest(
        "PUT",
        "/twitter/tweet/1",
        Collections.<String, String>emptyMap(),
        entity);

The ContentType that you specify for the HttpEntity is important because it will be used to set the Content-Type header so that Elasticsearch can properly parse the content. Future releases of Elasticsearch will require this to be set properly.

Note that the low-level client doesn’t expose any helper for json marshalling and un-marshalling. Users are free to use the library that they prefer for that purpose.

The underlying Apache Async Http Client ships with different org.apache.http.HttpEntity implementations that allow to provide the request body in different formats (stream, byte array, string etc.). As for reading the response body, the HttpEntity#getContent method comes handy which returns an InputStream reading from the previously buffered response body. As an alternative, it is possible to provide a custom org.apache.http.nio.protocol.HttpAsyncResponseConsumer that controls how bytes are read and buffered.

The following is a basic example of how async requests can be sent:

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();