Pass raw json string query to Elastic Search using java

I have got the data from Elasticsearch index by using the below code:

SearchRequest request = new SearchRequest("football_sum_csv").scroll(new TimeValue(60000));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//    searchSourceBuilder.query(matchQuery("multi", "test"));
searchSourceBuilder.sort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
SearchResponse scrollResp =, RequestOptions.DEFAULT);

This will return all the data from my index of ElasticSearch.

In here, I want to filter some data based on my query. In my case, I want to manually enter query and get results from ElasticSearch.

For example:

This below query will return all the data as like above

query = {'query': {'bool': {'must': [{'match_all': {}}], 'must_not': [], 'should': []}} }

This below query will return all the data in the Country named Spain

query = {"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}}

This below query will return all the data in the os named Windows and sessionTime between 1000 and 5000

{"query": {"bool": {"must": [{"range": {"sessionTime": {"gte": 1000, "lt": 5000}}}, {"match_phrase": {"os": "Windows"}}], "must_not": [], "should": []}}}

In the above three queries, they perform different operation in ElasticSearch. I want to use this like queries to get my data.

If I put query inside here in above java code,

searchSourceBuilder.query({"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}});

It gives me error.
I know Querybuilders has lots of query options such as range, match and so on. I don't know how to make it. Please help me with some solutions.

Found the Answer:

wrapperQuery needs to be used for passing query as json

String query = "{"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}";
QueryBuilder qb = QueryBuilders.wrapperQuery(query);
SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder();
SearchRequest searchRequest = new SearchRequest("index_name");
SearchResponse scrollResp1 =, RequestOptions.DEFAULT);

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.