ElasticSearch provides scripting support for sorting functionality. In real-world applications, there is often a need to modify the score using an algorithm that depends on the context and some external variables. Some common scenarios are as follows:
You need a working ElasticSearch cluster and an index populated with the script used for facet processing, available in the online code.
For sorting using scripting, we will perform the following steps:
price
field multiplied by a factor
parameter (usually VAT), 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 '{ "query": { "match_all": {} }, "sort": { "_script" : { "script" : "doc["price"].value * factor", "type" : "number", "ignore_unmapped" : true, "params" : { "factor" : 1.1 }, "order" : "asc" } } }'
In this case we have used a match_all
query and a sort
script.
{ "took" : 7, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1000, "max_score" : null, "hits" : [ { "_index" : "test-index", "_type" : "test-type", "_id" : "161", "_score" : null, "_source" : …, "sort" : [ 0.0278578661440021 ] }, { "_index" : "test-index", "_type" : "test-type", "_id" : "634", "_score" : null, "_source" : …, "sort" : [ 0.08131364254827411 ] }, { "_index" : "test-index", "_type" : "test-type", "_id" : "465", "_score" : null, "_source" : …, "sort" : [ 0.1094966959069832 ] } ] } }
The sort
parameter, which we discussed in Chapter 5, Search, Queries, and Filters, can be extended with the help of scripting.
The sort
scripting allows defining several parameters, such as:
order (default "asc") ("asc" or "desc")
: This determines whether the order must be ascending or descending.script
: This contains the code to be executed.type
: This defines the type to convert the value.params
(optional, a JSON object): This defines the parameters to be passed to.ignore_unmapped
(optional): This ignores unmapped fields in sort. This flag allows us to skip problems due to missing fields in shards.Extending the sort with scripting allows the use of a broader approach in scoring your hits.
MVEL provides a lot of built-in functions that can be used in scripts such as:
If you want to retrieve records in a random order, you can use a script with a random method as shown in the following code:
curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?&pretty=true&size=3' -d '{ "query": { "match_all": {} }, "sort": { "_script" : { "script" : "Math.random()", "type" : "number", "params" : {} } } }'
18.188.35.158