ElasticSearch 根据字段值的计数提升相关性

ElasticSearch boosting relevance based on the count of the field value

我正在尝试根据字段值的计数来提高相关性。字段值的计数越少,相关性越高。

比如我有1001个文档。 John 写了 1000 份文档,而 Joe 只写了一份。

// 1000 documents by John
{"title": "abc 1", "author": "John"}
{"title": "abc 2", "author": "John"}
// ...
{"title": "abc 1000", "author": "John"}

// 1 document by Joe
{"title": "abc 1", "author": "Joe"}

当我针对标题字段搜索 "abc" 时,我会得到 1001 个文档。如果这些文档不完全相同,它们应该具有非常相似的相关性分数。字段值 "John" 的计数是 1000,字段值 "Joe" 的计数是 1。现在,我想提高文档 {"title": "abc 1", "author": "Joe"} 的相关性,否则,它将是真的很难看到作者Joe的文档

谢谢!

如果有人遇到相同的用例,我将使用 Function Score Query 来解释我的解决方法。这种方式至少会调用 Elasticsearch 服务器两次。

  1. 获取每个人的计数(您可以使用聚合功能)。在我们的示例中,我们从 John 那里得到 1000,从 Joe 那里得到 1。
  2. 根据计数生成权重。计数越多,相关权重越小。像 John 的 1 + sqrt(1/1000) 和 Joe 的 1 + sqrt(1/1)
  3. 使用脚本中的权重根据作者的数值计算分数(脚本可以好很多):

    {
    "query": {
        "function_score": {
            "query": {
                "match": { "title": "abc" }
            },
            "script_score" : {
                "script" : {
                  "inline": "if (doc['author'].value == 'John') {return (1 + sqrt(1/1000)) * _score}\n return (1 + sqrt(1/1)) * _score;"
                }
            }
        }
    }
    }