"bucket_script" aggregation initialization exception

Hi, This is my query:
{
"aggs": {
"users": {
"cardinality": {
"field": "user_id.keyword"
},
"aggs": {
"time": {
"sum": {
"field": "ts_duration"
}
},
"avg_time": {
"bucket_script": {
"buckets_path": { "totaluser": "users", "totaltime": "time"},
"script": "totaltime / totaluser"
}}}}}}

and I got this error:

{
"error": {
"root_cause": [
{
"type": "aggregation_initialization_exception",
"reason": "Aggregator [users] of type [cardinality] cannot accept sub-aggregations"
}
],
"type": "aggregation_initialization_exception",
"reason": "Aggregator [users] of type [cardinality] cannot accept sub-aggregations"
},
"status": 500
}
What that's means ? Thank you

There are two problems with your request. For starters, you have nested the three aggregations inside each other. And as the error already suggests: a cardinality aggregation cannot accept sub-aggregations. All three aggregations need to be at the same level.

Furthermore, the bucket_script aggregation can only be nested inside a multi-bucket aggregation. That may change in the future (you can follow the work on this Github issue), but for now you have to use a workaround. You can nest the bucket_script aggregation inside a filters aggregation that only has one filter, with a match_all query. It's not pretty, but it gets the work done:

{
  "size": 0,
  "aggs": {
    "all_data": {
      "filters": {
        "filters": {
          "all": {
            "match_all": {}
          }
        }
      },
      "aggs": {
        "users": {
          "cardinality": {
            "field": "user_id.keyword"
          }
        },
        "time": {
          "sum": {
            "field": "ts_duration"
          }
        },
        "avg_time": {
          "bucket_script": {
            "buckets_path": {
              "totaluser": "users",
              "totaltime": "time"
            },
            "script": "params.totaltime / params.totaluser"
          }
        }
      }
    }
  }
}

(By the way, please format any code snippets on this forum using the </> button. It makes your post much easier to read and it's more likely that someone will help you that way :slight_smile: )

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