# Ordering by a field value in Terms Aggregation

**URL:** <https://discuss.elastic.co/t/ordering-by-a-field-value-in-terms-aggregation/155100>\
**Category:** Elasticsearch\
**Created:** [November 2, 2018, 1:57am UTC](https://discuss.elastic.co/t/ordering-by-a-field-value-in-terms-aggregation/155100 "2018-11-02T01:57:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Karthik\_ek](https://avatars.discourse-cdn.com/v4/letter/k/c68b51/32.png) [@Karthik\_ek](https://discuss.elastic.co/u/Karthik_ek)\
**Post date:** [November 2, 2018, 1:57am UTC](https://discuss.elastic.co/t/ordering-by-a-field-value-in-terms-aggregation/155100/1 "2018-11-02T01:57:52Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 30, 2018, 1:57am UTC](https://discuss.elastic.co/t/ordering-by-a-field-value-in-terms-aggregation/155100/2 "2018-11-30T01:57:55Z")

</div>

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