gpt4 book ai didi

Elasticsearch 查询 : Multiply final score using nested object and function score

转载 作者:行者123 更新时间:2023-11-29 02:56:25 25 4
gpt4 key购买 nike

我有包含一些数据和特定省略列表的文档(参见 mappingexample data ):

我想编写一个执行以下操作的 ES 查询:

  1. 计算文档的一些“基本”分数(查询 1):

    {
    "explain": true,
    "query": {
    "bool": {
    "should": [
    {
    "constant_score": {
    "filter": {
    "term": {
    "type": "TYPE1"
    }
    }
    }
    },
    {
    "function_score": {
    "linear": {
    "number": {
    "origin": 30,
    "scale": 20
    }
    }
    }
    }
    ]
    }
    }
    }
  2. 最后根据特定 id 的省略百分比乘以分数(在示例中我使用 omit valut for A"omit.id": "A")。作为查询 2 中的演示,我计算了这个乘数。

    {
    "query": {
    "nested": {
    "path": "omit",
    "query": {
    "function_score": {
    "query": {
    "filtered": {
    "query": {
    "match_all": {}
    },
    "filter": {
    "term": {
    "omit.id": "A"
    }
    }
    }
    },
    "functions": [
    {
    "linear": {
    "omit.percent": {
    "origin": 0,
    "scale": 50,
    "offset": 0,
    "decay": 0.5
    }
    }
    }
    ],
    "score_mode": "multiply"
    }
    }
    }
    }
    }

为了实现这个最终乘法,我遇到了以下问题:

  • 如果我在嵌套查询中计算线性函数分数,(根据我的解释)我不能在 function_score 查询中使用任何其他字段。
  • 我无法将计算出的分数与封装到嵌套查询中的任何其他 function_score 相乘。

我想寻求解决此问题的任何建议。

请注意,也许我应该摆脱这种嵌套类型并改用键值对。例如:

{
"omit": {
"A": {
"percent": 10
},
"B": {
"percent": 100
}
}
}

但不幸的是会有很多键,这会导致巨大的(不断增长的)映射,所以我不喜欢这个选项。

最佳答案

至少我想出了一个基于“非嵌套方式”的可能解决方案。完整脚本可见here .

我按照问题中的描述修改了省略列表:

"omit": {
"A": {
"percent": 10
},
"B": {
"percent": 100
}
}

此外,我将 enabled 标志设置为 false 以在映射中不包含这些元素:

"omit": {
"type" : "object",
"enabled" : false
}

最后一个技巧是使用 script_score 作为 function_score 的函数,因为只有在那里我才能使用 percent 的值 _source.omit.A.percent脚本:

{
"query": {
"function_score": {
"query": {
...
},
"script_score": {
"lang": "groovy",
"script": "if (_source.omit.A){(100-_source.omit.A.percent)/100} else {1}"
},
"score_mode": "multiply"
}
}
}

关于Elasticsearch 查询 : Multiply final score using nested object and function score,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26651979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com