Home > front end >  How to query all values of a nested field with Elasticsearch
How to query all values of a nested field with Elasticsearch

Time:07-19

I would like to query a value in all data packages I have in Elasticsearch.

For example, I have the code :

  "website" : "google",
  "color" : [
    {
      "color1" : "red",
      "color2" :  "blue"
    }
  ]
} 

I have this code for an undefined number of website. I want to extract all the "color1" for all the websites I have. How can I do ? I tried with match_all and "size" : 0 but it didn't work.

Thanks a lot !

CodePudding user response:

To be able to query nested object you would need to map them as a nested field first then you can query nested field like this:

GET //my-index-000001/_search
{
  "aggs": {
    "test": {
      "nested": {
        "path": "color"
      },
      "aggs": {
        "test2": {
          "terms": {
            "field": "color.color1"
          }
        }
      }
    }
  }
}

Your result should look like this for the query:

"aggregations": {
    "test": {
        "doc_count": 5,
        "test2": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "red",
                    "doc_count": 4
                },
                {
                    "key": "gray",
                    "doc_count": 1
                }
            ]
        }
    }
}

if you check the aggregation result back you will have list of your color1 with number of time it appeared in your documents.

For more information you can check Elasticsearch official documentation about Nested Field here and Nested aggregation here.

  • Related