How to use ElasticSearch JSON DSL in Java?

Tags: , , ,

I’m working on a springboot project and having some trouble with ElasticSearch. The user will put some JSON-format elasticsearch DSL query strings in the database and they are black-box to me. What I need to do is get the query strings and use them so search information in elasticsearch.

In python, the DSL can be a parameter like this:

body = {

How can I perform the search without knowing the details of the string and just using the JSON format query in Java?


I believe there are two ways to do it in modern ES client libraries. I haven’t tried them myself, but first one seems to be pretty straightforward.

First one is using low-level client:

Request request = new Request("POST", "/index/_search");
Response response = client.performRequest(request);

Seems like it’s enough just to push JSON as string into setJsonEntity, and you’re already set.

Second one is to use high level client, and this gets tricky, though it can provide more robust API. As you might know, elasticsearch has concept of XContent, which is serialization/deserialization to/from different formats, including JSON. Theoretically, it is possible to create JsonXContentParser, which then can be used to instantiate SearchSourceBuilder:


The problem is only that JsonXContentParser requires number of arguments to be instantiated, and i’m not sure how to properly create those dependencies.

Source: stackoverflow