Ordering nested aggregation

When executing a aggregation using nested objects, I get the following error when sorting on a metric:
Sub-path [nested] points to non single-bucket aggregation.

According to ElasticSearch 2.2 NestedAggregation, a nested aggregation actually is single-bucket.

Source for aggregation validation that is throwing this error can be found at:
aggregations/support/AggregationPath.java

Query

{
  "aggregations": {
    "titleGroup": {
      "terms": {
        "field": "documenTitle",
        "order": {
          "nested > cardinality": "desc"
        }
      },
      "aggregations": {
        "nested": {
          "nested": {
            "path": "nested_object"
          },
          "aggregations": {
            "cardinality": {
              "cardinality": {
                "field": "nested_object.hash"
              }
            }
}}}}}}

Error

{
  "error": {
    "root_cause": [
      {
        "type": "aggregation_execution_exception",
        "reason": "Invalid terms aggregation order path [nested>cardinality]. Terms buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end. Sub-path [nested] points to non single-bucket aggregation"
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "bitsensor",
        "node": "7uApA39rQOGMX4soKZQung",
        "reason": {
          "type": "aggregation_execution_exception",
          "reason": "Invalid terms aggregation order path [nested>cardinality]. Terms buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end. Sub-path [nested] points to non single-bucket aggregation"
        }
      }
    ]
  },
  "status": 500
}

Mapping

{
  "properties": {
    "documenTitle": {"type":"string"},
    "nested_object": {
      "type": "nested",
      "properties": {
        "hash": {
          "type": "long"
}}}}}

@Ruben_van_Vreeland indeed this is a bug, see https://github.com/elastic/elasticsearch/issues/16838#issuecomment-190210463 for more information on this. You can also track that issue on Github.

1 Like