简体   繁体   中英

How to use Nested Aggregation on Elasticsearch?

I am pretty new to elasticsearch. I am writing a nested dsl using aggregation.

Structure of Input Document is something like this:

   {
        "_source": {
           "id": 1234,
           "oid": 6,

            "education": [
              {
                 "school_name": "Harvard",
                 "city" : "Boston",
                 "year": 1965,
                 "degree": "Undergrad"
              },
              {
                 "school_name": "Harvard",
                 "city" : "Boston",
                 "year": 1975,
                 "degree": "Masters"
              },
              {
                 "school_name": "Harvard",
                 "city" : "Boston",
                 "year": 1958,
                 "degree": "BA"
              }  
           ],
        }
     },

----Another records... and so on

*Above shown document complies to one record.

Goal: I am trying to find out all those students who studied in Boston. So Ideally if I have only above document then I should get only 1 record.

With the nested aggregation query I have written below I am getting 3 as a count for Boston

GET cluster_test/index_test/_search
{
"query": {
 "bool": {
  "must": [
    {
      "term": {
        "oid": {
          "value": "6"
        }
      }
    }
  ]
}
},
 "aggs": {
    "education": {
      "nested": {
        "path": "education"
      },
      "aggs": {
        "edu": {
          "terms": {
            "field": "education.city",
            "size": 0
          }
        }
      }
    }
  }
}         

If anyone can point out where I am going wrong or what is better to deal with these type of queries. Any help is appreciated.

You shouldn't be using aggregations as you want to filter students who studied on desired city. Using filters like below should help.

GET cluster_test/index_test/students/_search
{
"filtered" : {
    "query" : { "match_all" : {} },
    "filter" : {
        "nested" : {
            "path" : "education",
            "filter" : {
                "bool" : {
                    "must" : [
                        {
                            "term" : {"education.city" : "Boston"}
                        }
                    ]
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM