ElasticSearch - Sort by another field which is not mentioned in field section aggregation query

I want to perform aggregation on a certain results and then sort it. While aggregation query works fine. We want to sort the results based on another parameter and not the aggregated field. Say for example I want to aggregate by StudyAggregation field but sort by StudyDescription field (returned from the top hits):-

{ "size": 0, "from": 0, "query": { "bool": { "must": [ { "query_string": { "fields": [], "query": "*pt*" } } ] } }, "aggs": { "sources": { "terms": { "size": 150, "field": "StudyAggregation", "order": { "_key": "desc" } }, "aggs": { "latest": { "top_hits": { "size": 1, "_source": [ "StudyDescription" ] } } } }, "distinct_count": { "cardinality": { "field": "StudyAggregation.keyword" } } } }

Right now it is sorting by StudyAggregation. We want to sort it by StudyDescription but since the values can be duplicate we're using StudyAggregation to get unique results(StudyDescription is showed in the UI which uses StudyAggregation in the backend to fetch unique results)

.Can anyone help suggest any approaches for the same?

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