Leibale Eidelman
Leibale Eidelman

Reputation: 3184

ElasticSearch: count by item in array

For every document I have a category array, it looks like this:

[{
    "id": 1,
    "level": 1
}, {
    "id": 2,
    "level": 2
}, {
    "id": 3,
    "level": 3
}]

How can I count the categories I have in every document according to the level 3 category.id?

Upvotes: 0

Views: 1221

Answers (1)

Pratyusha Rasamsetty
Pratyusha Rasamsetty

Reputation: 21

category array shall be nested field. And the rest can be handled via aggregations. Try something similar to the code given below.

"aggregations": {
"mainAgg": {
  "nested": {
    "path": "category"
  },
  "aggs": {
    "levelFilter": {
        -- filter condition
      "filter": {
        "term": {
          "level": 3
        },
          -- count aggregation
        "aggs": {
          "count": {
            "value_count": {
              "field": "level"
            }
          }
        }
      }
    }
  }
}

}

Upvotes: 1

Related Questions