如何提升弹性搜索中的特定术语?

How to boost specific terms in elastic search?

如果我有以下映射:

PUT /book
{
  "settings": {},
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      },
      "author": {
        "type": "text"
      }
    }
  }
}

我怎样才能提升特定作者高于其他作者? 对于以下示例:

PUT /book/_doc/1
{
  "title": "car parts",
   "author": "john smith"
}

PUT /book/_doc/2
{
  "title": "car",
   "author": "bob bobby"
}

PUT /book/_doc/3
{
  "title": "soap",
   "author": "sam sammy"
}

PUT /book/_doc/4
{
  "title": "car designs",
   "author": "joe walker"
}

GET /book/_search
{
   "query": {  
      "bool": {                    
        "should": [
             { "match": { "title": "car" }},
              { "match": { "title": "parts" }} 
         ]
       }
   }
}

如何才能让我的搜索结果中 "joe walker" 的书籍位于搜索结果的顶部?

一种解决方案是利用 function_score.

The function_score allows you to modify the score of documents that are retrieved by a query.

From here

根据您的映射,尝试 运行 这个查询,例如:

GET book/_search
{
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "should": [
            {
              "match": {
                "title": "car"
              }
            },
            {
              "match": {
                "title": "parts"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "filter": {
            "match": {
              "author": "joe walker"
            }
          },
          "weight": 30
        }
      ],
      "max_boost": 30,
      "score_mode": "max",
      "boost_mode": "multiply"
    }
  }
}

function_score 中的 query 与您使用的 should 查询相同。

现在我们要获取查询的所有结果,并为 joe walker 的书籍赋予更多权重(增加分数),这意味着它的书籍优先于其他书籍。

为了实现这一点,我们创建了一个函数(在 functions 内),该函数计算由 joe walker 本书过滤的查询返回的每个文档的新分数。

您可以调整权重和其他参数。

希望对您有所帮助