从 function_score 访问查询值以计算新分数

access query value from function_score to compute new score

我需要自定义ES分数。我需要实现的评分函数是:

score = len(document_term) - len(query_term)

例如,我在 ES 索引中的文档之一是:

{
  "name": "foobar"
}

和搜索查询

{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "name": {
            "query": "foo"
          }
        }
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": "doc['name'].value.length() - ?LEN(query_tem)?"
            }
          }
        }
      ],
      "boost_mode": "replace"
    }
  }
}

上面的搜索应该提供 6 - 3 = 3 的分数。但是我没有找到访问查询词值的解决方案。

是否可以在 function_score 上下文中访问查询词的值?

没有直接的方法可以做到这一点,但是您可以通过以下方式实现,您需要在 two different 中添加查询参数查询的 部分

在那条重要说明之前,如果字段的类型为 text, instead you would need to have its sibling field created as keyword,则不能应用 doc['myfield'].value 并在脚本中引用它,我在下面再次提到:

映射:

PUT myindex
{
  "mappings" : {
    "properties" : {
      "myfield" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      }
    }
  }
}

示例文档:

POST myquery/_doc/1
{
  "myfield": "I've become comfortably numb"
}

查询:

POST <your_index_name>/_search
{
  "query": {
    "function_score": {
      "query": {
        "match": {
          "myfield": "numb"
        } 
      },
      "functions": [
        {
          "script_score": {
            "script": {
              "source": "return doc['myfield.keyword'].value.length() - params.myquery.length()",
              "params": {
                "myquery": "numb"          <---- Add the query string here as well
              }
            }
          }
        }
      ],
      "boost_mode": "replace"
    }
  }
}

回复:

{
  "took" : 558,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 24.0,
    "hits" : [
      {
        "_index" : "myindex",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 24.0,
        "_source" : {
          "myfield" : "I've become comfortably numb"
        }
      }
    ]
  }
}

希望对您有所帮助!