0

当我尝试向我的 Elasticsearch 发出 query_string 请求时,该请求使用 function_score ( script_score) 来操纵其默认分数。但我似乎总是得到一个基础_score1.0

我的模型如下所示:

{
    "name": "Secret Birthday Party",
    "description": "SECRET! Discuss with discretion",
    "_userCounters": [
        {
            "user": "king",
            "count": 12
        },
        {
            "user": "joseph",
            "count": 1
        }
    ]
}

我对 function_score 脚本的请求如下所示:

    {
    "query" : {
        "function_score" : {
            "query": {
                "query_string": {
                    "query": "secret",
                    "analyze_wildcard": true,
                    "fields": [
                        "name", "description"
                    ]
                }
            },
            "script_score": {
                "script": {
                    "inline" : "int scoreBoost = 1; for (int i = 0; i < params['_source']['_userCounters'].length; i++) { if (params['_source']['_userCounters'][i].user == 'joseph') { scoreBoost += params['_source']['_userCounters'][i].count; } } return scoreBoost;"
                }
            }
        }
    }
}

我得到的是一个可以准确找到我想要的结果,但只返回 function_score 脚本中的值。内置评分似乎不再起作用。这是我得到的回应:

{
    "_index": "test3",
    "_type": "projects",
    "_id": "7",
    "_score": 2, // this is exactly the return value of the script_score. What I want instead is that this value gets multiplied with the normal score of ES
    "_source": {
        "name": "Secret Birthday Party",
        "description": "SECRET! Discuss with discretion",
        "_userCounters": [
            {
                "user": "queen",
                "count": 12
            },
            {
                "user": "daniel",
                "count": 1
            }
        ]
    }
}

我的猜测是我的请求正文格式不正确,因为所有分数都只是1.0当我完全取出 function_score 时。

4

1 回答 1

0

我想到了。这实际上是脚本本身的问题,而不是请求正文的结构。

该函数仅返回应该与_score值相乘的因子。相反,它需要自己进行乘法运算。

这是更易读的脚本:

int scoreBoost = 1;

for (int i = 0; i < params['_source']['_userData'].length; i++) {
if (params['_source']['_userData'][i].user == '{userId}') {
        scoreBoost += params['_source']['_userData'][i].count;
    }
}

// the error was here: only the scoreBoost value was returned
// the fix is to multiply it with the _score value
return _score * scoreBoost;
于 2018-01-03T16:21:43.050 回答