# Script sort by descending order

**URL:** <https://discuss.elastic.co/t/script-sort-by-descending-order/144254>\
**Category:** Elasticsearch\
**Created:** [August 13, 2018, 11:04pm UTC](https://discuss.elastic.co/t/script-sort-by-descending-order/144254 "2018-08-13T23:04:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Xiaofeng\_Zhan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/xiaofeng_zhan/32/34448_2.png) [@Xiaofeng\_Zhan](https://discuss.elastic.co/u/Xiaofeng_Zhan)\
**Post date:** [August 13, 2018, 11:04pm UTC](https://discuss.elastic.co/t/script-sort-by-descending-order/144254/1 "2018-08-13T23:04:36Z")

</div>

Hello,  
I need to write a painless sorting script, sorting by first name and last name, descending order.

The existing script is sorting by first name and last name, ascending order.  
The script is like below

```
String ALPHABETICAL_SORT_SCRIPT = "[doc['preferredFirstName.raw'].value, doc['preferredLastName.raw'].value,"
 + ".stream()"
 + ".filter(x -> x != null && !x.isEmpty())" + ".map(String::toLowerCase)"
 + ".collect(Collectors.joining('', '', '~'))"

```

Then I use Java API ScriptSortBuilder to build sort script with input ALPHABETICAL\_SORT\_SCRIPT. And it works well.

The sort result list is like:  
Adam Doe  
Bob Doe  
Cathy Doe  
Cathy Johnson  
Doug Weiss  
...

Now I am trying to write a similar script to sort by first name and last name by _descending_ order. The expect result should be the reverse order of above list. But I got stuck.  
Any one can help?  
Thanks!

---

<div class="post-metadata">

**Author:** ![rjernst](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rjernst/32/6363_2.png) [@rjernst](https://discuss.elastic.co/u/rjernst)\
**Post date:** [August 14, 2018, 6:45pm UTC](https://discuss.elastic.co/t/script-sort-by-descending-order/144254/2 "2018-08-14T18:45:00Z")

</div>

You should be able to do this without a script. The sort parameter can take multiple sort criteria.

```auto
GET /my_index/_search
{
    "sort" : [
        { "preferredFirstName.raw" : "desc"},
        { "preferredLastName.raw" : "desc" }
    ],
    "query" : {
        "match_all": {}
    }
}

```

This will be much more efficient than generating the sort key in a script, since it can utilize the ordinals present within docvalues.

---

<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:** [September 11, 2018, 6:52pm UTC](https://discuss.elastic.co/t/script-sort-by-descending-order/144254/3 "2018-09-11T18:52:13Z")

</div>

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