Ordering by a field value in Terms Aggregation

Hi,

I'm looking to order the search results by specific field values. I'm not able to do it using the Aggregation Order. When I tried using the scripted metric, I'm getting below error:

org.elasticsearch.search.aggregations.AggregationExecutionException: Invalid terms aggregation order path [scriptedAgg]. Terms buckets can only be sorted on a sub-aggregator path that is built out of zero or more single-bucket aggregations within the path and a final single-bucket or a metrics aggregation at the path end.

Below is the code that I tried:(modified with a basic example)

TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("termsAggName").size(1000).script(new Script("doc['empNumber'].value + ' | ' + doc['empName'].value))).subAggregation(AggregationBuilders.topHits("subTermsAggName").size(1));

ScriptedMetricAggregationBuilder scriptedMetricBuilder = AggregationBuilders.scriptedMetric("scriptedAgg");

scriptedMetricBuilder.mapScript(new Script("doc['empDesignation'].value == 'Developer'"));

termsAggregationBuilder.order(Terms.Order.aggregation("scriptedAgg", true)).subAggregation(scriptedMetricBuilder);

SearchResponse searchResponse = elasticsearchTemplate.getClient().prepareSearch().setIndices(indexName).setTypes(typeName).setQuery(booleanQuery).addAggregation(termsAggregationBuilder).execute().actionGet();

The aggregation works fine. I'm facing trouble when I try to order the buckets by Employee Designation.

The code highlighted in italics is the new code I tried for ordering by field value(s).

Please help me in achieving the order.

Thanks in advance!

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