You can tell Elasticsearch to run an expensive query, such as a script or geolocation, using post filter. The query in the post filter is only executed after the main query is executed so that the number of documents the expensive query has to be executed on is minimum. In the following query, we will run the script query as post filter:
POST chapter7/product/_search
{
"query": {
"match": {
"product_name": "iphone"
}
},
"post_filter": {
"script": {
"script": {
"lang": "painless",
"inline": "params._source.containsKey('variations') && params._source.variations.length > params.num_of_variations",
"params": {
"num_of_variations": 1
}
}
}
...