嵌套对象数组的elasticsearch查询

2eafrhcq  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(3)|浏览(481)

我在elasticsearch上遇到一个查询问题。我记录了这类物体:

{
    "obj_id": 1,
    "label": "label obj 1",
    "array_of_nested": [{
            "nested_id": 1,
            "label": "label nested obj1"
        }, {
            "nested_id": 2,
            "label": "label nested obj2"
        }
    ]
}, {
    "obj_id": 2,
    "label": "label obj 2",
    "array_of_nested": [{
            "nested_id": 3,
            "label": "label nested obj1"
        }, {
            "nested_id": 4,
            "label": "label nested obj2"
        }
    ]
}

我正在尝试编写一个查询,以在\u nested属性的数组\u中查找嵌套的\u id为2的所有对象,但到目前为止无法使其工作:/
谢谢您!

busg9geu

busg9geu1#

添加工作示例 mapping , example docs ,和 working 搜索查询。需要使用嵌套字段的路径参数
Map

{
    "mappings": {
        "properties": {
            "array_of_nested": {
                "type": "nested"
            },
            "obj_id" :{
                "type" : "text"
            },
            "label" :{
                "type" : "text"
            }
        }
    }
}

样本文档

{
    "obj_id": 1,
    "label": "label obj 1",
    "array_of_nested": [
        {
            "nested_id": 1,
            "label": "label nested obj1"
        },
        {
            "nested_id": 2,
            "label": "label nested obj2"
        }
    ]
}

还有第二个医生

{
    "obj_id": 2,
    "label": "label obj 2",
    "array_of_nested": [
        {
            "nested_id": 3,
            "label": "label nested obj1"
        },
        {
            "nested_id": 4,
            "label": "label nested obj2"
        }
    ]
}

搜索查询

{
    "query": {
        "nested": {
            "path": "array_of_nested",
            "query": {
                "term": {
                    "array_of_nested.nested_id": {
                        "value": "2"
                    }
                }
            }
        }
    }
}

以及你期望的搜索结果

"hits": [
            {
                "_index": "nestedobj",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "obj_id": 1,
                    "label": "label obj 1",
                    "array_of_nested": [
                        {
                            "nested_id": 1,
                            "label": "label nested obj1"
                        },
                        {
                            "nested_id": 2,
                            "label": "label nested obj2"
                        }
                    ]
                }
            }
        ]
mgdq6dx1

mgdq6dx12#

在嵌套类型中,需要定义 path 在您的查询中,您的查询如下:

{
  "query": {
    "nested": {
      "path": "array_of_nested",
      "query": {
        "term": {
          "array_of_nested.nested_id": {
            "value": "2"
          }
        }
      }
    }
  }
}
mwg9r5ms

mwg9r5ms3#

你能试试这个吗?

{
  "query": {
    "match": {
      "array_of_nested.nested_id": 2
    }
  }
}

相关问题