gpt4 book ai didi

elasticsearch - 检查数组是否包含 Elasticsearch 中具有特定字段的对象?

转载 作者:行者123 更新时间:2023-12-05 09:35:50 24 4
gpt4 key购买 nike

我是 Elastic Search 的新手,我的数据具有以下形式:

索引映射

{
"company:product:index": {
"aliases": {},
"mappings": {
"company:product:mapping": {
"properties": {
"attribute_heel-style": {
"properties": {
"label": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"source": {
"type": "keyword"
},
"value": {
"type": "keyword"
},
"value_label": {
"type": "keyword"
}
}
}
}
}
}
}
}

索引数据

{
"attribute_heel-style": [
{
"name": "heel-style",
"label": "Heel Style",
"value": "stiletto",
"value_label": "Stiletto"
},
{
"name": "heel-style",
"label": "Heel Style",
"value": "wedge"
"value_label": "Wedge"
},
... // a bunch of other objects in this array as well
]
}

我想创建一个查询,以便我可以过滤数组中键“value_label”的值为“Wedge”的所有对象。我该怎么做?

编辑:找到解决方案!在下面发帖。感谢@EsCoder。

{
"query": {
"bool": {
"filter": [
{
"bool": {
"must": [
{
"term": {
"attribute_heel-style.value_label": "wedge"
}
}
]
}
}
]
}
}
}

最佳答案

Arrays of objects do not work as you would expect: you cannot queryeach object independently of the other objects in the array. If youneed to be able to do this then you should use the nested data typeinstead of the object data type.

引用这个ES official document在数组上获得详细解释。

添加带有索引数据、映射、搜索查询和搜索结果的工作示例

应用嵌套数据类型后,您必须重新索引数据

索引映射:

{
"mappings": {
"properties": {
"attribute_heel-style": {
"type": "nested"
}
}
}
}

索引数据:

{
"attribute_heel-style": [
{
"name": "heel-style",
"label": "Heel Style",
"value": "stiletto",
"value_label": "Stiletto"
},
{
"name": "heel-style",
"label": "Heel Style",
"value": "wedge",
"value_label": "Wedge"
}
]
}

搜索查询:

{
"query": {
"nested": {
"path": "attribute_heel-style",
"query": {
"bool": {
"filter": [
{
"match": {
"attribute_heel-style.value_label": "Wedge"
}
}
]
}
},
"inner_hits":{}
}
}
}

搜索结果:

"inner_hits": {
"attribute_heel-style": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.0,
"hits": [
{
"_index": "65585632",
"_type": "_doc",
"_id": "1",
"_nested": {
"field": "attribute_heel-style",
"offset": 1
},
"_score": 0.0,
"_source": {
"name": "heel-style",
"label": "Heel Style",
"value": "wedge",
"value_label": "Wedge" // note this
}
}
]
}
}
}
}

更新 1:

{
"mappings": {
"company:product:mapping": {
"properties": {
"attribute_heel-style": {
"type": "nested", // note this
"properties": {
"label": {
"type": "keyword"
},
"name": {
"type": "keyword"
},
"source": {
"type": "keyword"
},
"value": {
"type": "keyword"
},
"value_label": {
"type": "keyword"
}
}
}
}
}
}
}

关于elasticsearch - 检查数组是否包含 Elasticsearch 中具有特定字段的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65585632/

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