# Elasticsearch JAVA Query with nesting

**URL:** <https://discuss.elastic.co/t/elasticsearch-java-query-with-nesting/189870>\
**Category:** Elasticsearch\
**Created:** [July 10, 2019, 8:48pm UTC](https://discuss.elastic.co/t/elasticsearch-java-query-with-nesting/189870 "2019-07-10T20:48:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dhughes](https://avatars.discourse-cdn.com/v4/letter/d/7ab992/32.png) [@dhughes](https://discuss.elastic.co/u/dhughes)\
**Post date:** [July 10, 2019, 8:48pm UTC](https://discuss.elastic.co/t/elasticsearch-java-query-with-nesting/189870/1 "2019-07-10T20:48:29Z")

</div>

We have two fields in our Elasticsearch index, one is called 'Command' and the other is called 'Code'.

What I'm looking to do is have a 'terms' match for 2 possible values for Command. Then, for each of the 2 Commands , have a must match for them.

So, something like:

QueryBuilder qb = QueryBuilders  
.boolQuery()  
.must(termsQuery("Command.keyword", "TypeA", "TypeB"))  
.must(termsQuery("Code.keyword", "TypeACodeA", "TypeACodeB", "TypeBCodeA", "TypeBCodeB"))

The problem is, I believe that I will get too many potential matches - ones I don't want, such as a Command of 'TypeA' to a Code of 'TypeBCodeA'. What I'm looking for is query results that ONLY include:

Command TypeA matched to TypeACodeA OR TypeACodeB,  
OR,  
Command TypeB matched to TypeBCodeA or TypeBCodeB

I know that there's nested queries, sub queries, etc, although for these other techniques how I would apply them. Any suggestions would be great.

- David H.

---

<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:** [August 7, 2019, 8:48pm UTC](https://discuss.elastic.co/t/elasticsearch-java-query-with-nesting/189870/2 "2019-08-07T20:48:29Z")

</div>

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