Search code examples
elasticsearchnestelasticsearch-2.0

Elasticsearch for index array element


Hi i want to search array element from index using elastic search query

{
  "name": "Karan",
  "address": [
                        {
                            "city": "newyork",
                            "zip": 12345
                        },
                        {
                            "city": "mumbai",
                            "zip": 23456
                        }]
}}

when i am trying to search using match query it does not work

{
    "query": {
      "bool": {
        "must": [
          {
            "match": {
              "address.city": "newyork"
            }
          }
        ]
      }
    }
  }

when i access simple feild like "name": "Karan" it works, there is only issue for array element.


Solution

  • Because nested objects are indexed as separate hidden documents, we can’t query them directly. Instead, we have to use the nested query to access them:

    GET /my_index/blogpost/_search
    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "title": "eggs" 
              }
            },
            {
              "nested": {
                "path": "comments", 
                "query": {
                  "bool": {
                    "must": [ 
                      {
                        "match": {
                          "comments.name": "john"
                        }
                      },
                      {
                        "match": {
                          "comments.age": 28
                        }
                      }
                    ]
                  }
                }
              }
            }
          ]
    }}}
    

    See the docs