Sorting results by a scripted field


(Richard Corbishley) #1

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" } }
            }
        }
    }
}

(system) #2