2

我正在努力解决 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"
        }
    ]
}

我正在尝试编写一个查询以在 array_of_nested 属性中查找所有nested_id 为 2 的对象,但到目前为止无法使其工作。:/

谢谢 !

4

3 回答 3

2

你能试试这个吗?

{
  "query": {
    "match": {
      "array_of_nested.nested_id": 2
    }
  }
}
于 2020-10-20T13:05:40.990 回答
1

mapping使用、example docsworking搜索查询添加工作示例。您需要使用嵌套字段的路径参数

映射

{
    "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"
                        }
                    ]
                }
            }
        ]
于 2020-10-20T13:18:16.037 回答
1

In nested types you need to define path in your query and your query would be something like this:

{
  "query": {
    "nested": {
      "path": "array_of_nested",
      "query": {
        "term": {
          "array_of_nested.nested_id": {
            "value": "2"
          }
        }
      }
    }
  }
}
于 2020-10-20T12:47:43.217 回答