# Named Query Confusion

**URL:** <https://discuss.elastic.co/t/named-query-confusion/271997>\
**Category:** Elasticsearch\
**Created:** [May 3, 2021, 2:16pm UTC](https://discuss.elastic.co/t/named-query-confusion/271997 "2021-05-03T14:16:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bsmith](https://avatars.discourse-cdn.com/v4/letter/b/7feea3/32.png) [@bsmith](https://discuss.elastic.co/u/bsmith)\
**Post date:** [May 3, 2021, 2:16pm UTC](https://discuss.elastic.co/t/named-query-confusion/271997/1 "2021-05-03T14:16:01Z")

</div>

I understand that named queries add the matched\_queries property to the response, but is there any way to access documents that match the named queries in aggregations?

The goal is to be able to use the "%dashboard\_context-must\_clause%" for dynamic time ranges, but I haven't been able to find a way to do bool queries inside of aggregations.

```auto
"query": {
    "bool": {
      "must": [
        {"match": {"year-month": {"query": "2021-01", "_name": "A"}}},
        {"match": {"year-month": {"query": "2021-03", "_name": "B"}}}
      ]
    }
  },
"aggs": {
  "calcs": {
     "terms": {
        "script": "'do stuff'"
      },
      "aggs": {
        "A_calc":{ 
          //I want to only use the results from query A here
          "filter": { "term": { "meat":"steak" } },
          "aggs" : {
            "steakcount": {
              "value_count": {
                "field": "meat"
              }
            }
          }
        },
        "B_calc":{ 
          //I want to only use the results from query B here
          "filter": { "term": { "meat":"chicken"} },
          "aggs" : {
            "chickencount": {
              "value_count": {
                "field": "meat"
              }
            }
          }
        },

```

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [May 10, 2021, 9:25am UTC](https://discuss.elastic.co/t/named-query-confusion/271997/2 "2021-05-10T09:25:37Z")

</div>

Hey,

you need to repeat the query within each `aggregation filter`, so you would have a `bool` query that contains `meat:streak` and `year-month: 2021-01` in its `filter clause`.

Hope that helps!

--Alex

---

<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:** [June 7, 2021, 9:25am UTC](https://discuss.elastic.co/t/named-query-confusion/271997/3 "2021-06-07T09:25:53Z")

</div>

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