Nested Query in query building


I have to run the following query in one of the index, "my_index"

String query = "sanjay OR sanju AND vijay OR vijji AND brothers OR Cousins";

My requirement is that, this shoud search for

(sanjay OR sanju) AND (vijay OR vijji) AND (brothers OR Cousins). 

Instead it is searching for

sanjay OR (sanju AND vijay) OR (vijji AND brothers) OR Cousins

Currently I'm using

      BoolQueryBuilder qbuilder = new BoolQueryBuilder();
	String[] orSplitArr = query.toLowerCase().split("\\s+or\\s+");
	for (String q : orSplitArr) {
		if (q.contains(" and ")) {
			String[] andSplitArr = q.split("\\s+and\\s+");
			for (int i = 0; i < andSplitArr.length; i++)
			     qbuilder.must(QueryBuilders.matchQuery("_all", q));
		qbuilder.should(QueryBuilders.matchQuery("_all", q));

	SearchRequestBuilder req = con.getClient().prepareSearch("Index_Name");
	req = req.setSearchType(SearchType.DFS_QUERY_AND_FETCH);
	req = req.setQuery(qbuilder);

	SearchResponse res = req.execute().actionGet();

Please guide me in solving this.

Sanjay Reddy.

The bool query builder does not change depending on the order in which should call must and should. In your inner loop, instead of typing:


You should have


where X is a second bool query that has the left and right hand sides of your "AND" statement.

1 Like