6

For one of my ElasticSearch queries, I'd like to define define a function score and sort by it. The function score takes the computed score and adds a boost value to it. Each document has its boost value stored in a numeric field.

Like this:

{
    "from": 0,
    "size": 10,
    "query": {
        "function_score": {
            "functions": [
                {
                    "script_score": {
                        "script": "_score + doc['boostFactor'].value"
                    }
                }
            ],
            "query": {
                "filtered": {
                    "query": {
                        "query_string": {
                            "query": "search for this!"
                        }
                    }
                }
            },
            "boost_mode": "replace"
        }
    }
}

So far so good, this works fine. Now here's the problem: going forward, each document will have an array of boost values:

"boostFactor": [ 0, 0.5, 1, 3 ]

When firing up the query, I'd like the script score to pick a particular element of the array, based on a predefined index. So let's say index=2, then the script score would potentially look like this:

                "script_score": {
                    "script": "_score + doc['boostFactor'][2].value"
                }

Unfortunately, ElasticSearch doesn't accept this:

...Query Failed [Failed to execute main query]]; 
nested: CompileException[[Error: unexpected token in constructor]...

Any ideas?

1 Answer 1

7

doc['boostFactor'].value returns a single value. To get the whole array, use doc['boostFactor'].values; then you can get a specific index within the array as you'd expect:

            {
                "script_score": {
                    "script": "_score + doc['boostFactor'].values[2]"
                }
            }

See the scripting section of the Elasticsearch docs for more info: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html

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

1 Comment

The problem with this method is that the doc['boostFactor'] does not preserve the order of the array elements. See: elasticsearch-users.115913.n3.nabble.com/…

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.