如何匹配 Elasticsearch 中对象数组中的所有对象?
How do I match by all objects in an array of objects in Elasticsearch?
我想从 Elasticsearch 中获取像下面这样的匹配文档。
{
"configurationId": "dp4wb8kpw4k1s2z",
"type": 1,
"items": [
{
"text": "car",
"rank": 1
},
{
"text": "ship",
"rank": 2
}
],
"date": "2021-07-08"
}
但我想要对项目数组中的所有对象进行匹配,并且我希望获得包含该匹配项的文档。例如items数组中rank值为1的对象的文本值肯定是“car”,数组中rank值为2的对象的文本值肯定是“ship”。
如何在 Elasticsearch 中为此编写查询?
您需要在 Elasticsearch 中使用嵌套对象而不是对象数组。
Arrays of objects do not work as you would expect: you cannot query
each object independently of the other objects in the array. If you
need to be able to do this then you should use the nested data type
instead of the object data type.
有关更多信息,请在此处查看有关数组和嵌套对象的 Elasticsearch 官方文档 here。
将映射更改为嵌套对象后,您将能够像这样查询:
查询:
GET my-index-000001/_search
{
"query": {
"nested": {
"path": "items",
"query": {
"bool": {
"must": [
{ "match": { "items.text": "car" }},
{ "match": { "items.rank": 1 }}
]
}
}
}
}
}
我想从 Elasticsearch 中获取像下面这样的匹配文档。
{
"configurationId": "dp4wb8kpw4k1s2z",
"type": 1,
"items": [
{
"text": "car",
"rank": 1
},
{
"text": "ship",
"rank": 2
}
],
"date": "2021-07-08"
}
但我想要对项目数组中的所有对象进行匹配,并且我希望获得包含该匹配项的文档。例如items数组中rank值为1的对象的文本值肯定是“car”,数组中rank值为2的对象的文本值肯定是“ship”。
如何在 Elasticsearch 中为此编写查询?
您需要在 Elasticsearch 中使用嵌套对象而不是对象数组。
Arrays of objects do not work as you would expect: you cannot query each object independently of the other objects in the array. If you need to be able to do this then you should use the nested data type instead of the object data type.
有关更多信息,请在此处查看有关数组和嵌套对象的 Elasticsearch 官方文档 here。
将映射更改为嵌套对象后,您将能够像这样查询:
查询:
GET my-index-000001/_search
{
"query": {
"nested": {
"path": "items",
"query": {
"bool": {
"must": [
{ "match": { "items.text": "car" }},
{ "match": { "items.rank": 1 }}
]
}
}
}
}
}