专业编程基础技术教程

网站首页 > 基础教程 正文

ElasticSearch系列-搜索-评分(function_score)

ccvgpt 2024-10-12 15:01:19 基础教程 69 ℃

score_mode 与 boost_mode 的区别


boost_mode

ElasticSearch系列-搜索-评分(function_score)


将全文搜索的相关度分值乘以field_value_factor函数的结果,对最终分值的影响可能太大了。通过boost_mode参数,我们可以控制函数的结果应该如何与_score结合在一起,该参数接受下面的值:

  • multiply:_score乘以函数结果(默认情况)
  • sum:_score加上函数结果
  • min:_score和函数结果的较小值
  • max:_score和函数结果的较大值
  • replace:将_score替换成函数结果
GET /blogposts/post/_search
{
  "query": {
    "function_score": {
      "query": {
        "multi_match": {
          "query":    "popularity",
          "fields": [ "title", "content" ]
        }
      },
      "field_value_factor": {
        "field":    "votes",
        "modifier": "log1p",
        "factor":   2
      },
      "boost_mode": "sum" 
    }
  }
}

新分数公式:

new_score = old_score + log(1 + 0.1 * number_of_votes)

不指定 "boost_mode": "sum" 公式 , boot_mode默认乘以

new_score = old_score * log(1 + factor * number_of_votes)

score_mode


每个函数都会返回一个结果,我们需要某种方法将多个结果归约成一个,然后将它合并到原始的_score中去。

score_mode参数指定了该归约操作,它可以取下面的值:

  • multiply: 函数结果会相乘(默认行为)
  • sum:函数结果会累加
  • avg:得到所有函数结果的平均值
  • max:得到最大的函数结果
  • min:得到最小的函数结果
  • first:只使用第一个函数的结果,该函数可以有过滤器,也可以没有

例如:我们希望对每个函数的结果进行相加来得到最终的分值,因此使用的是score_mode是sum

GET /_search
{
  "query": {
    "function_score": {
      "filter": { 
        "term": { "city": "Barcelona" }
      },
      "functions": [ 
        {
          "filter": { "term": { "features": "wifi" }}, 
          "weight": 1
        },
        {
          "filter": { "term": { "features": "garden" }}, 
          "weight": 1
        },
        {
          "filter": { "term": { "features": "pool" }}, 
          "weight": 2 
        }
      ],
      "score_mode": "sum", 
    }
  }
}

实例

{
  "function_score" : {
    "query" : {
      "bool" : {
        "must" : [ {
          "term" : {
            "isCollect" : 0
          }
        } ]
      }
    },
    "functions" : [ {
      "field_value_factor" : {
        "field" : "initScore",
        "missing" : 0.0
      }
    }, {
      "exp" : {
        "updateTime" : {
          "origin" : "now",
          "scale" : "1d",
          "decay" : 0.8,
          "offset" : "1d"
        }
      }
    } ],
    "score_mode" : "sum",
    "boost_mode" : "sum"
  }
}

score_mode定义的是如何将各个function的分值合并成一个综合的分值;

boost_mode则定义如何将这个综合的分值作用在原始query产生的分值上。


score = func1[] + func2[]

boost_mode 作用于func内部, 用于原始_score与函数结果的计算

score_mode 作用于func1、func2、....


以上案例:

score = func_factor(_score + initScore) + func_exp(_score....)


最近发表
标签列表