我需要定制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上下文中访问查询术语的值?
发布于 2019-06-13 10:56:16
没有直接的方法来做到这一点,但是您可以通过下面的方式实现这一点,您需要在查询的两个不同部分中添加查询参数。
在此之前,如果字段类型为doc['myfield'].value
,则不能应用text
,而是需要将其同级字段创建为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"
}
}
]
}
}
希望这能有所帮助!
https://stackoverflow.com/questions/56578291
复制相似问题