How to get the json representation of the ElasticSearch query/request that was built with Java API Client (7.16)?

Viewed 792

A new Java API Client was released in the 7.16 version of ES and the Java Rest Client was deprecated. There was the ability to convert a query to JSON in the deprecated client. It was convenient for debugging/tuning/profiling of the query in Kibana.

Unfortunately, I don't see any mention of this in the new client documentation. So my question is:

Is it possible to get a JSON representation of the query that was constructed via the Java API Client? It can be either some utility class or log config of the client that prints outgoing requests.

3 Answers

The only way I found so far is to put a conditional breakpoint in co/elastic/clients/transport/rest_client/RestClientTransport.java:215 from elasticsearch-java-7.16.2.jar and check the value of baos variable.

It looks like this feature will be directly supported in an upcoming version: https://discuss.elastic.co/t/elaticsearch-java-client-output-dsl/300952

In the meantime, there is a workaround given in the above discussion, but it does not quite work. Here is a snippet that works for me:

StringWriter writer = new StringWriter();
JsonGenerator generator = JacksonJsonProvider.provider().createGenerator(writer);
request.serialize(generator, new JacksonJsonpMapper());
generator.flush();
return writer.toString();

As a temporary method waiting for pull request mentionned below, i just used

// TODO delete when https://github.com/elastic/elasticsearch-java/pull/213
public static String serializeToString(Query q) {
    return q._get().toString();
}

It does not print anything pretty but it covers my use case of string comparison for tests.

Related