# Sorting results by a scripted field

**URL:** <https://discuss.elastic.co/t/sorting-results-by-a-scripted-field/813>\
**Category:** Elasticsearch\
**Created:** [May 18, 2015, 2:13am UTC](https://discuss.elastic.co/t/sorting-results-by-a-scripted-field/813 "2015-05-18T02:13:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rcorbish](https://avatars.discourse-cdn.com/v4/letter/r/ee59a6/32.png) [@rcorbish](https://discuss.elastic.co/u/rcorbish)\
**Post date:** [May 18, 2015, 2:13am UTC](https://discuss.elastic.co/t/sorting-results-by-a-scripted-field/813/1 "2015-05-18T02:13:56Z")

</div>

I like elastic search a lot, I am having trouble with one thing: sorting results by a scripted result.

I would like to sort the below query by absolute value of margin: e.g if totalMargin were the following, it would sort as follows

-1,000,000  
-999,999  
999,998  
-999,997

This query works for positive values. I can do two of these and merge the results ...

```
 {
    "size": 0, 
    "aggs" : {
        "netMargin" : {
            "terms" : {
                "field" : "clientTicker" , 
                "order" : { "totalMargin" : "desc" }
            },
            "aggs" : {
                "totalMargin" : { "sum" : { "field" : "margin" } }
            }
        }
    }
}
```

---

<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:** [July 6, 2017, 12:13am UTC](https://discuss.elastic.co/t/sorting-results-by-a-scripted-field/813/2 "2017-07-06T00:13:36Z")

</div>


