Sorting based on distinct counts

Using cardinality aggs, I'm able to get the distinct count of elements.

Instead of aggs, we want to get the list of matching elements using query. And this query, we would like to get it sorted using the distinct count. I looked into the function score query, but using that I'm not able to get the distinct count of a particular field.

How can I do this - to calculate the score based on the distinct count.

I don't know any way for you to achieve this. Why aren't aggregations a method for you to apply?

@DiscussBuster we want to show the list of documents sorted by the most users who have seen that error. There is a parent child relationship and we want to count the users in the child type and then find the parent types. Hence, I assume this won't work with aggregations.