3

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.

igor
  • 699
  • 1
  • 9
  • 26

4 Answers4

3

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();
Cameron
  • 1,868
  • 3
  • 21
  • 38
1

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.

igor
  • 699
  • 1
  • 9
  • 26
1

In my case @Cameron answer didn't work, because returned only a part of the query. Besides it I also need to serialize the date.
So I ended up with the next solution:

String extractQuery(SearchRequest searchRequest) {
    // jsonpMapper can be extracted to static field
    JacksonJsonpMapper jsonpMapper = new JacksonJsonpMapper()
    jsonpMapper.objectMapper().registerModule(new JavaTimeModule())
    jsonpMapper.objectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"))

    StringWriter writer = new StringWriter()
    JacksonJsonpGenerator generator = new JacksonJsonpGenerator(new JsonFactory().createGenerator(writer))
    searchRequest.serialize(generator, jsonpMapper)
    generator.flush()
    return writer.toString()
}
Max
  • 766
  • 9
  • 19
0

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.

Makz23
  • 28
  • 5