For your specific question, the script needs a nested context, as is the case with the term
request.
This can be rewritten for ES 1.x:
curl -XGET 'localhost:9200/test/_search' -d' { "query": { "nested": { "path": "skills", "query": { "filtered": { "filter": { "term": { "skills.skill_id": 100 } }, "query": { "function_score": { "functions": [ { "script_score": { "script": "sqrt(1.2 * doc['skills.recommendations_count'].value)" } } ] } } } } } } }'
For ES 2.x (filters became first-class citizens in ES 2.x, so the syntax has changed a bit to catch up!):
curl -XGET 'localhost:9200/test/_search' -d' { "query": { "nested": { "path": "skills", "query": { "bool": { "filter": { "term": { "skills.skill_id": 100 } }, "must": { "function_score": { "functions": [ { "script_score": { "script": "sqrt(1.2 * doc['skills.recommendations_count'].value)" } } ] } } } } } } }'
Note. I made a term
a term
request because it does not have a logical effect on the evaluation (this is either an exact match or not). I also added the name of the nested field to the term
filter, which is a requirement in Elasticsearch 2.x and later (and earlier practice).
With this in mind, you can (and should) avoid using a script whenever possible. This is one such case. function_score
supports the concept of the field_value_factor
function, which allows you to do what you are trying, but completely without a script . You can also specify a “missing” value to control what happens if the field is missing.
This means exactly the same script, but it will work better:
curl -XGET 'localhost:9200/test/_search' -d' { "query": { "nested": { "path": "skills", "query": { "filtered": { "filter": { "term": { "skills.skill_id": 100 } }, "query": { "function_score": { "functions": [ { "field_value_factor": { "field": "skills.recommendations_count", "factor": 1.2, "modifier": "sqrt", "missing": 0 } } ] } } } } } } }'
For ES 2.x:
curl -XGET 'localhost:9200/test/_search' -d' { "query": { "nested": { "path": "skills", "query": { "bool": { "filter": { "term": { "skills.skill_id": 100 } }, "must": { "function_score": { "functions": [ { "field_value_factor": { "field": "skills.recommendations_count", "factor": 1.2, "modifier": "sqrt", "missing": 0 } } ] } } } } } } }'
The scripts are slow and they also involve using fielddata in Elasticsearch 1.x, which is bad . You mentioned the values of doc, which is a promising start that suggests using Elasticsearch 2.x, but that can only be terminology.
If you are just starting out with Elasticsearch, I highly recommend starting with the latest version.