Sorting "children" aggregations

I am looking to aggregate children based on parent fields, but I want to filter on both children and parent fields. The problem is when I do this, I get results where parents match the criteria but no children match the criteria and because the parents which match the criteria have many children, these entries are at the top of the list.

As a result, I want to order the "children" aggregation based on the number of children which match the criteria and order the parent aggregation based on that ordering. Can I achieve this?

Below is the query structure and problematic results

{
"aggregations" : {
“parentFilter" : {
"filter" : {
"bool" : {
"must" : {
"match_all" : { }
}
}
},
"aggregations" : {
“parentCount" : {
"terms" : {
"field" : “parentField",
"size" : 10,
"order" : {
“childCount" : "desc"
}
},
"aggregations" : {
“childCount" : {
"children" : {
"type" : “childType"
},
"aggregations" : {
“filteredChildren" : {
"filter" : {
"bool" : {
"must" : {
"terms" : {
“childField" : [ “childCriteria" ]
}
}
}
}
}
}
}
}
}
}
}
}
}

Result:
"aggregations": {
“parentFilter": {
"doc_count": 105,
“parentCount": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": “field2",
"doc_count": 6,
“childCount": {
"doc_count": 50,
"filteredChildren": {
"doc_count": 0
}
}
},
{
"key": “field0",
"doc_count": 7,
"childCount": {
"doc_count": 30,
"filteredChildren": {
"doc_count": 5
}
}
},
{
"key": “field1",
"doc_count": 7,
“childCount": {
"doc_count": 30,
"filteredChildren": {
"doc_count": 4
}
}
}
]
}
}
}

Desired Result:
"aggregations": {
“parentFilter": {
"doc_count": 105,
“parentCount": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": “field0",
"doc_count": 7,
"childCount": {
"doc_count": 30,
"filteredChildren": {
"doc_count": 5
}
}
},
{
"key": “field1",
"doc_count": 7,
“childCount": {
"doc_count": 30,
"filteredChildren": {
"doc_count": 4
}
},
{
"key": “field2",
"doc_count": 6,
“childCount": {
"doc_count": 50,
"filteredChildren": {
"doc_count": 0
}
}
}
}
]
}
}
}

Is there anyway to achieve this ordering?

Hi All. I have sorted it out.

To the current ordering - I added an aggregation path.

so "order" : {"childCount" : "desc"} becomes "order" : {"childCount>childFilter" : "desc"}

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