Kiba
Kiba

Reputation: 399

Elasticsearch count elements in array, for a property having a value

I have a document with structure like this:

{
  "products": [
    {
      "variants": [
        {
          "type": "type_1"
        },
        {
          "type": "type_2"
        }
      ]
    }
  ]
}

"variants" are dynamic mapping. I want to count variants having a particular type. If i use terms aggregation it will return me bucket keys of all types and their respective doc count but i want types that i pass to be present in the bucket keys and their respective doc count.

Or is their any way to only count variants instead of doc and get buckets with type as key and value as their count

Can anybody please help me with the query?

Upvotes: 2

Views: 2621

Answers (1)

Kiba
Kiba

Reputation: 399

I solved it using script.

{
  "aggs": {
    "agg_terms_types": {
      "terms": {
        "script": {
          "source": "params.selected_types",
          "params": {
            "selected_types": [
              "type_1"
            ]
          }
        }
      }
    }
  }
}

Upvotes: 2

Related Questions