Sorting data using script
ElasticSearch provides scripting support for the sorting functionality. In real world applications, there is often a need to modify the default sort by the match score using an algorithm that depends on the context and some external variables. Some common scenarios are given as follows:
- Sorting places near a point
- Sorting by most-read articles
- Sorting items by custom user logic
- Sorting items by revenue
Getting ready
You will need a working ElasticSearch cluster and an index populated with the script used in Chapter 6, Aggregations, which is available at https://github.com/aparo/elasticsearch-cookbook-second-edition.
How to do it...
In order to sort using scripting, perform the following steps:
- If you want to order your documents by the
price
field multiplied by afactor
parameter (that is, sales tax), the search will be as shown in the following code:curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?&pretty=true&size=3' -d '{ "...