# Nested Query in query building

**URL:** <https://discuss.elastic.co/t/nested-query-in-query-building/57009>\
**Category:** Elasticsearch\
**Created:** [August 2, 2016, 1:12pm UTC](https://discuss.elastic.co/t/nested-query-in-query-building/57009 "2016-08-02T13:12:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sanju1323](https://avatars.discourse-cdn.com/v4/letter/s/5daacb/32.png) [@sanju1323](https://discuss.elastic.co/u/sanju1323)\
**Post date:** [August 2, 2016, 1:12pm UTC](https://discuss.elastic.co/t/nested-query-in-query-building/57009/1 "2016-08-02T13:12:05Z")

</div>

Hi,

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));
			continue;
		}
		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.

Regards,  
Sanjay Reddy.

---

<div class="post-metadata">

**Author:** ![leeavital](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/leeavital/32/11151_2.png) [@leeavital](https://discuss.elastic.co/u/leeavital)\
**Post date:** [August 2, 2016, 4:48pm UTC](https://discuss.elastic.co/t/nested-query-in-query-building/57009/2 "2016-08-02T16:48:57Z")

</div>

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:

```auto
qbuilder.must(...)

```

You should have

```auto
qbuilder.should(X)

```

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

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:30pm UTC](https://discuss.elastic.co/t/nested-query-in-query-building/57009/3 "2017-07-05T22:30:39Z")

</div>


