# Elasticsearch aggregation on a field with dynamic properties

**URL:** <https://discuss.elastic.co/t/elasticsearch-aggregation-on-a-field-with-dynamic-properties/265667>\
**Category:** Elasticsearch\
**Created:** [February 26, 2021, 8:42pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-on-a-field-with-dynamic-properties/265667 "2021-02-26T20:42:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gkeswani92](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/gkeswani92/32/84633_2.png) [@gkeswani92](https://discuss.elastic.co/u/gkeswani92)\
**Post date:** [February 26, 2021, 8:42pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-on-a-field-with-dynamic-properties/265667/1 "2021-02-26T20:42:32Z")

</div>

Given the following mapping where variants are a `nested` type and options is a `flattened` type:

```auto
{
  "doc_type" : "product",
  "id" : 1,
  "variants" : [
    {
      "options" : {
        "Size" : "XS",
      },
      "price" : 1,
    },

    {
      "options" : {
        "Size" : "S",
        "Material": "Wool"
      },
      "price" : 6.99,
    },
  ]
} 

```

I want to run an aggregation that produces data in the following format:

```auto
{
  "variants.options.Size": {
    "buckets" : [
      {
        "key" : "XS",
        "doc_count" : 1
      },
      {
        "key" : "S",
        "doc_count" : 1
      },
    ],
  },
  "variants.options.Material": {
    "buckets" : [
      {
        "key" : "Wool",
        "doc_count" : 1
      }
    ],
  },
} 

```

I could very easily do something like:

```auto
"aggs": {
    "variants.options.Size": {
      "terms": {
        "field": "variants.options.Size"
      }
    },
    "variants.options.Material": {
      "terms": {
        "field": "variants.options.Material"
      }
    }
  }

```

The caveat here is that we're using the `flattened` type for options because the fields in options are **dynamic** and so there is no way for me to know before hand that we want to aggregate on `Size` and `Material`.

Essentially, I want to tell Elasticsearch that it should aggregate on whatever keys it finds under `options`. Is there a way to do this?

---

<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:** [March 26, 2021, 8:42pm UTC](https://discuss.elastic.co/t/elasticsearch-aggregation-on-a-field-with-dynamic-properties/265667/2 "2021-03-26T20:42:48Z")

</div>

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