弹性script_score,仅计算特定的数组元素 [英] Elastic script_score, only count specific array elements
问题描述
我在Elastic中有一堆这样的对象:
{"id":"b397ab9c-2bab-4cce-a419-ba6b23545772",名称":"Alice",//省略其他字段" foo":[{"id":"1",酒吧":20},{"id":"2",酒吧":20}]},{"id":"826784cb-7dcd-4d2c-b444-a466032a7b06",名称":"Bob",//省略其他字段" foo":[{"id":"1",酒吧":15}]}
我试图根据 foo
中 id
为 2
的任何元素进行评分.因此,在上述对象中,爱丽丝得分为20,鲍勃得分为0(因为在他的 foo
数组中没有ID为 2
的元素.有点卡住如何让我的script_score查找特定元素.这是我的查询:
"query":{"function_score":{"score_mode":"max",功能":[{过滤器":{条款":{" foo.id" ;: {值":"2";}}},"script_score":{脚本":{" source" ;:" doc ['foo'].values/*此处的内容是什么?*/","params":{}}}}]}}
当 ,但没有 请注意,一旦进入 I have a bunch of objects like this one in Elastic: I am trying to make a score based on any elements in
When After you've reconfigured your mapping to be but without the Do note that once you're in the 这篇关于弹性script_score,仅计算特定的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! foo
的类型不是 nested
时,您将失去之间的连接id
和 bar
由于 filter
,因为那会过滤掉doc#2,因为它不符合该条件,并且您可能想执行某种脚本化的后备.嵌套
上下文,就无法访问 foo
数组中的其他对象组.换句话说,当您使用 id:2
时,您不会看到 id:1
组.更多信息此处.>{
"id" : "b397ab9c-2bab-4cce-a419-ba6b23545772",
"name": "Alice",
// other fields omitted
"foo" : [
{
"id" : "1",
"bar" : 20
},
{
"id" : "2",
"bar" : 20
}
]
},
{
"id" : "826784cb-7dcd-4d2c-b444-a466032a7b06",
"name": "Bob",
// other fields omitted
"foo" : [
{
"id" : "1",
"bar" : 15
}
]
}
foo
of which the id
is 2
. So in the above objects, Alice has a score of 20 and Bob has a score of 0 (as there's no element with id 2
in his foo
array. I'm however a bit stuck in how to have my script_score look for the specific element. Here is my query: "query": {
"function_score": {
"score_mode": "max",
"functions": [
{
"filter": {
"term": {
"foo.id": {
"value": "2"
}
}
},
"script_score": {
"script": {
"source": "doc['foo'].values /* what goes here? */",
"params": {
}
}
}
}
]
}
}
foo
is not of type nested
, you'll have lost the connection between id
and bar
due to value flattenning.nested
, you can do{
"query": {
"nested": {
"path": "foo",
"query": {
"function_score": {
"score_mode": "max",
"functions": [
{
"script_score": {
"script": {
"source": "if (doc['foo.id.keyword'].value == '2') { def bar = doc['foo.bar'].value; return bar } return 0",
"params": {}
}
}
}
]
}
}
}
}
}
filter
because that'd have filtered out doc#2 since it does not meet that condition and you probably want to do some sort of a scripted fallback.nested
context, you don't have access to other object groups in your foo
array. In other words, when you're in id: 2
, you don't see the id: 1
group. More info here.