2

Im generating a custom field using "script_fields". And I would like to use that field to generate score for the documents. How can I achieve this in elasticsearch. It would be great if any one could post an example query.

1 Answer 1

4

It's not really possible because when scores for the document are calculated the script field values are not computed yet. Search requests are typically executed in two phases: query and fetch. During the query phase scores are calculated and top documents are selected for retrieval. The list of the top documents is then used during fetch phase to retrieve the documents. During this retrieval process the script fields are calculated.

In other words in order to use script to score the documents, you need to use this script in the query phase by placing it into the function_score query, for example

Sign up to request clarification or add additional context in comments.

4 Comments

So, how to get intermediate return values out of the function_score query and return them with the results? ;)
@GabeKopley it's not possible unless 1) these values are the actual hit scores or 2) you want to implement the script as a java plugin (AKA native script) and store these intermediate values yourself in some static map. There simply no place where a script can "stash" these intermediate values between phases. The only information that is getting preserved between phases are scores and sort keys.
Thanks @imotov. And we can't return an arbitrary number of scores, just the one score, right? (that's what all the documentation suggests).
@GabeKopley Correct, each hit can only have one score. It can have an arbitrary number of sort keys, though. So if you will move your script from functions_score to sort, you will have more flexibility there. I would advise though to think twice if the potential benefit is worth the added complexity. The sort script is executed for every search result (could be millions of records), the field script is executed only for the records that you retrieve (typically 10). So, in most cases the overhead of recalculating the value in the script field should be minimal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.