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

时间:2019-06-13 10:15:21

标签: elasticsearch elasticsearch-painless

我需要自定义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上下文中访问查询词的值?

1 个答案:

答案 0 :(得分:1)

没有直接的方法可以执行此操作,但是您可以通过以下方式实现,您需要在 two 中添加查询参数查询部分

在此之前,如果字段的类型为text,则不能应用doc['myfield'].value,而是需要将其兄弟字段创建为keyword,并在其中引用该字段。脚本,我在下面再次提到:

映射:

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"
        }
      }
    ]
  }
}

希望这会有所帮助!