6.8. Sorting with scripts

Along with modifying the score of a document with a script, Elasticsearch allows you to use a script to sort documents before they’re returned to you. This can be useful if you need to sort on a field that doesn’t exist as a field in the document.

For example, imagine you’re searching for events about “elasticsearch” but you want to sort the groups by the number of people who attended; you can easily do this with the request shown in the following listing.

Listing 6.19. Sorting documents with a script

You should notice that you will get back a field in each matching document that looks like "sort": [5.0, 0.28856182]; these are the values that Elasticsearch has used to sort the documents. Notice that the 5.0 is a number; that’s because you specified to Elasticsearch that the output of your script was a number (as opposed to a string). The second value in the sort array is the original score of the document because you specified it as the next sort field in case the numbers of attendees match for multiple documents.

Although this is powerful, it’s much easier and faster to instead use the function _score query to influence the score of your document and sort by the _score instead of sorting using a custom script; that way all of your relevancy changes are in a single place (the query) instead of inside the sorting.

Another option is to have the number of attendees as another numeric field in the document that’s indexed. That makes sorting or changing the score using a function a lot easier to do.

Next, let’s take a little detour and talk about something that’s somewhat related to scripting but a little different: field data.