How can I dynamically generate the elastic search query based on some parameters

Viewed 1815

I have a requirement where I need to pass the elastic search query to the REST end_point like below:

{
    query : {
        match_all : {}
    }
}

So, to do this, lets say, I am getting parameters from UI. Like AND, OR, GroupBy, "text to search", etc..

How can I achieve this in Java to dynamically build the query string?

I am new to elastic search, so exploring on the way to produce the query string.

Any suggestions would help.

EDIT 1: May be another way of asking the above: How can I convert "SearchSourceBuilder" or "QueryBuilder" to Json?

1 Answers

please have a look on the elasticsearch java client search api here: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search.html

using the high level rest client for java is nearly the same as the api above, but it will make your code more future proof as the way to connect to a cluster will change in upcoming release: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html

both of the apis will build the query for you and take care of the request and response handling. but if you want to see the resulting json query string, you can always invoke toString() method on the QueryBuilder object.

Here a Example for High Level REST Client:

org.elasticsearch.index.query.QueryBuilders.matchAllQuery().toString() 
{
  "match_all" : {
    "boost" : 1.0
  }
}

Using in a SearchSourceBuilder gives you even a more complete JSON:

 MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();

 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
 searchSourceBuilder.query(matchAllQuery);

Then searchSourceBuilder.toString() yields

{"query":{"match_all":{"boost":1.0}}}

And here using the Java-API:

SearchRequestBuilder searchRequestBuilder = client.prepareSearch("index1", "index2")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("multi", "test"))                 
                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     
                .setFrom(0).setSize(60).setExplain(true);

Invoking searchRequestBuilder.toString() results in a complete JSON representation of this query:

{"from":0,"size":60,"query":{"term":{"multi":{"value":"test","boost":1.0}}},"post_filter":{"range":{"age":{"from":12,"to":18,"include_lower":true,"include_upper":true,"boost":1.0}}},"explain":true}
Related