Access the matched analysed term in script_score?

I am using function_score to supply my custom script to compute the score, I know I can access the field value via "doc['field'].value", but how do you access the actual matched term?

In fact, what I wanted to achieve is to calculate the score based on the number of characters matched in an analysed field, e.g. for a field with value "Pete Alex", when querying for "Peter" with an edge_ngram analyzer (i.e. querying "P", "Pe", "Pet", "Pete", "Peter"), I want to return a score of len(matched_term)/len(search_term) = len("Pete")/len("Peter") = 4/5 = 0.8.

I can create a script_score like this:

"script_score": {
    "script": {
        "source": "doc['field'].value.length()*1.0/params.term.length()",
        "params": {
            "term": "Peter"
        }
    }
}

But it only works if "doc['field'].value" does not have spaces or other delimiters (e.g. if the field is just "Pete" instead of "Pete Alex"). How do I access the matched analysed term (i.e. "Pete" in this case) in script_score?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.