In Chapter 5, Search, we've seen many filters. Elasticsearch scripting allows the extension of a traditional filter with custom scripts.
Using scripting to create a custom filter is a convenient way to write scripting rules not provided by Lucene or Elasticsearch, and to implement business logic not available in a DSL query.
You need an up-and-running Elasticsearch installation as we described in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.
To execute curl
via the command-line you need to install curl
for your operating system.
To correctly execute the following commands, you need an index populated with the script (chapter_09/populate_for_scripting.sh
) available in the online code and Javascript/Python Language scripting plugins installed.
For filtering a search using script, we will perform the following steps:
curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search? pretty&size=3' -d '{ "query": { "bool": { "filter": { "script": { "script": { "inline": "doc["age"].value > params.param1", "params": { "param1": 80 } } } } } } }'
In this example, all documents, in which the age value is greater than param1
, are taken as qualified for return.
{ "took" : 30, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 237, "max_score" : 1.0, "hits" : [ { "_index" : "test-index", "_type" : "test-type", "_id" : "9", "_score" : 1.0, "_source" :{ ... "age": 83, ... } }, { "_index" : "test-index", "_type" : "test-type", "_id" : "23", "_score" : 1.0, "_source" : { ... "age": 87, ... } }, { "_index" : "test-index", "_type" : "test-type", "_id" : "47", "_score" : 1.0, "_source" : {.... "age": 98, ...} } ] } }
The script filter is a language script that returns a boolean value (true
/false
). For every hit, the script is evaluated and if it returns true
, the hit passes the filter. This type of scripting can only be used as Lucene filters, not as queries, because it doesn't affect the search.
The script code can be any code in your preferred supported scripting language that returns a boolean value.
Using other languages is very similar to Painless/Groovy.
For the current example, I have chosen a standard comparison that works in several languages. To execute the same script using the JavaScript language, the code is:
curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?pretty&size=3' -d '{ "query": { "script": { "script": { "inline": "doc["age"].value > param1", "lang": "javascript", "params": { "param1": 80 } } } } }'
For Python, we have the following code:
curl -XGET 'http://127.0.0.1:9200/test-index/test-type/_search?pretty&size=3' -d '{ "query": { "script": { "script": { "inline": "doc["age"].value > param1", "lang": "python", "params": { "param1": 80 } } } } }'
3.144.10.182