# Complex queries inside nested fields

**URL:** <https://discuss.elastic.co/t/complex-queries-inside-nested-fields/323514>\
**Category:** Elasticsearch\
**Created:** [January 19, 2023, 12:51pm UTC](https://discuss.elastic.co/t/complex-queries-inside-nested-fields/323514 "2023-01-19T12:51:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hemabh\_Ravee\_Fox](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hemabh_ravee_fox/32/111494_2.png) [@Hemabh\_Ravee\_Fox](https://discuss.elastic.co/u/Hemabh_Ravee_Fox)\
**Post date:** [January 19, 2023, 12:51pm UTC](https://discuss.elastic.co/t/complex-queries-inside-nested-fields/323514/1 "2023-01-19T12:51:32Z")

</div>

I have some documents which contain a nested field `planList` which is an array of objects. It's length will always be 2 or 3. And the objects always have 3 keys - planName, planType, and planId.

I want to write a query which will return a list of all planNames, along with the most frequent plan that it was present with and it's frequency.

For example, consider the following 4 documents -

```auto
{planList: [{planName: a, planType: x, planId: 1},{planName: b, planType: x, planId: 2}]}
{planList: [{planName: a, planType: x, planId: 1},{planName: b, planType: x, planId: 2},{planName: c, planType: y, planId: 3}]}
{planList: [{planName: a, planType: x, planId: 1},{planName: c, planType: y, planId: 3}]}
{planList: [{planName: d, planType: y, planId: 4},{planName: c, planType: y, planId: 3}]}

```

The response for this data should be something like -  
plan A was found with plan B and plan C 2 times (draw between plan B and C)  
plan B was found with plan A 2 times  
plan C was found with plan A 2 times  
plan D was found with plan C one time

The query to get to these docs is very simple -

```auto
"query": {
    "bool": {
      "must": [
        {
          "match": {
            "event": "comparePlans"
          }
        }
      ]
    }
  }

```

Can someone please help me with the aggregations needed to get the insight I'm looking for?  
Thanks.

---

<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:** [February 16, 2023, 12:52pm UTC](https://discuss.elastic.co/t/complex-queries-inside-nested-fields/323514/2 "2023-02-16T12:52:21Z")

</div>

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