How to sort composite aggregation by sub-aggregation

Viewed 22

I have 2 indices of posts and comments. I want to get all posts/comments published by some user and sort them by numComments. The thing is that each comment is related to some post, meaning that i need to remove duplicates from the response and sort by the “original” post’s numComments. Another thing is that i need a pagination.

If i’m using composite aggregation, then i need to create buckets from the postId field but then to sort by sub-agg of numComments, which is not possible as far as i know. any idea?

{
  "size": 0,
  "aggs": {
    "posts_bucket": {
      "composite": {
        "size": 20,
        "sources": [
          {
            "postId": {
              "terms": {
                "field": "postId"
              }
            }
          }
        ],
        "after": { postId: 'lQhgnRm8q6T93HcyyEAO' } 
      },
      "aggs": {
        "sorting_aggs": {
          "max": {
            "field": "numComments"
          }
        }
      }
    }
  }
}
0 Answers
Related