Script sort by descending order

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?

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

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.

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