Sort single doc buckets by an aggregation on a nested collection

Hi everyone,
I am working on data modeling restaurants. A restaurants can have employees (which is a nested array of Employee) and an employee has a profession.
The idea behind the following query attempt is to return all restaurants which employ people in more than 3 distinct professions, sorted by the amount of distinct professions. Except for the sorting, the query runs perfectly fine, but I have trouble getting the sorting right.

Do you guys have any ideas? :slight_smile:

{
  "size": 0,
  "sort": [],
  "query": {
    "match_all": {}
  },
  "aggs": {
    "auxilary_id_grouping": {
      "terms": {
        "field": "_uid",
        "order": {
          "nested_employees_position_cardinality>employees_position_cardinality": "asc"
        }
      },
      "aggs": {
        "nested_employees_position_cardinality": {
          "nested": {
            "path": "employees"
          },
          "aggs": {
            "employees_position_cardinality": {
              "cardinality": {
                "field": "employees.position"
              }
            }
          }
        },
        "main_selector_agg": {
          "bucket_selector": {
            "script": {
              "inline": "(params.employees_position_cardinality) > (3)"
            },
            "buckets_path": {
              "employees_position_cardinality": "nested_employees_position_cardinality>employees_position_cardinality"
            }
          }
        },
        "auxilary_actual_document": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}

Noone here who can help? :slight_smile:

It's currently not possible to sort on nested aggregations (see this GitHub issue: https://github.com/elastic/elasticsearch/issues/16838 )

There's a fix coming in 6.1 that should resolve this issue.

1 Like

Great, thanks a lot! :slight_smile:

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