对嵌套对象数组的Elasticsearch查询

问题描述

我在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,{
            "nested_id": 4,"label": "label nested obj2"
        }
    ]
}

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

谢谢!

解决方法

你可以试试吗?

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

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

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

使用mappingexample docsworking搜索查询添加一个有效的示例。您需要使用path param of nested field

映射

{
    "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,{
            "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,"array_of_nested": [
                        {
                            "nested_id": 1,"label": "label nested obj1"
                        },{
                            "nested_id": 2,"label": "label nested obj2"
                        }
                    ]
                }
            }
        ]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...