Send Date to Elasticsearch from Java Rest Client

If you are getting HTTP/1.1 400 Bad Request while sending the date to elasticsearch from java code then try this

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = sdf.format(new Date());

Below is the sample snippet of Java Rest Low level Client which posts the data asynchronously to elasticsearch

JSONObject inputJson = new JSONObject();
inputJson.put("postDate", date);
RestClient restClient = null;
restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
String input = inputJson.toString();
ResponseListener listener = new ResponseListener()
{
@Override
public void onSuccess(Response a_response) {
System.out.println("Success..........");
}

@Override
public void onFailure(Exception exception) {
System.out.println("Failure:::" + exception.getMessage());
}
};
HttpEntity entity = new NStringEntity(input, ContentType.APPLICATION_JSON);
String endPoint = "/" + index + "/doc/";
if (where != null)
endPoint = index + "/doc/_update_by_query";
restClient.performRequestAsync(method, endPoint, Collections.emptyMap(), entity, listener);

Comments