gpt4 book ai didi

elasticsearch - Elasticsearch-匹配嵌套对象数组中的所有子项

转载 作者:行者123 更新时间:2023-12-03 02:30:44 26 4
gpt4 key购买 nike

我有这样的文件-
Doc1:

{
"attr1": "attrVal1",
"nestedAttr": [
{
"id": 1,
"type": "Type1",
"output": "PASS"
},
{
"id": 2,
"type": "Type2",
"output": "FAIL"
},
{
"id": 3,
"type": "Type1",
"output": "PASS"
}
]

}

Doc2:
{
"attr1": "attrVal1",
"nestedAttr": [
{
"id": 1,
"type": "Type2",
"output": "PASS"
},
{
"id": 2,
"type": "Type1",
"output": "FAIL"
},
{
"id": 3,
"type": "Type1",
"output": "PASS"
}
]

}


nestedAttr是嵌套映射的。我想搜索所有具有“type”:“Type1”和“output”:“PASS”的 attr1 。我不在乎Type2的输出,但是如果任何Type1在文档中包含FAIL,则应将其忽略。
因此,在上面的示例中,将为查询返回Doc1,而不会返回Doc2。

我尝试使用must和must_not进行排列组合的查询,但是所有查询都只是在嵌套对象中搜索至少一个匹配项。

最佳答案

假设已正确设置了嵌套对象/集合的映射,则可以使用nested query

准备:删除索引

DELETE test_nested

准备:设置嵌套映射
PUT test_nested
{
"mappings": {
"properties": {
"attr1": {
"type": "text"
},
"nestedAttr": {
"type": "nested",
"properties": {
"id": {
"type": "integer"
},
"type": {
"type": "keyword"
},
"output": {
"type": "keyword"
}
}
}
}
}
}

准备:创建文档#1
POST test_nested/_doc/1
{
"attr1": "attrVal1",
"nestedAttr": [
{
"id": 1,
"type": "Type1",
"output": "PASS"
},
{
"id": 2,
"type": "Type2",
"output": "FAIL"
},
{
"id": 3,
"type": "Type3",
"output": "PASS"
}
]
}

准备:创建文档#2
POST test_nested/_doc/2
{
"attr1": "attrVal1",
"nestedAttr": [
{
"id": 1,
"type": "Type2",
"output": "PASS"
},
{
"id": 2,
"type": "Type1",
"output": "FAIL"
},
{
"id": 3,
"type": "Type3",
"output": "FAIL"
}
]
}

搜索:(nestedAttr.type:Type1 AND nestedAttr.output:PASS)
POST /test_nested/_search
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "nestedAttr",
"query": {
"bool": {
"must": [
{
"match": {
"nestedAttr.type": "Type1"
}
},
{
"match": {
"nestedAttr.output": "PASS"
}
}
]
}
}
}
}
]
}
}
}

结果:count(nestedAttr.type:Type1 AND nestedAttr.output:PASS)= 1
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.7227666,
"hits" : [
{
"_index" : "test_nested",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.7227666,
"_source" : {
"attr1" : "attrVal1",
"nestedAttr" : [
{
"id" : 1,
"type" : "Type1",
"output" : "PASS"
},
{
"id" : 2,
"type" : "Type2",
"output" : "FAIL"
},
{
"id" : 3,
"type" : "Type3",
"output" : "PASS"
}
]
}
}
]
}
}

关于elasticsearch - Elasticsearch-匹配嵌套对象数组中的所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60072282/

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