Search code examples
elasticsearchnest

Nested Aggregation in Nest Elastic Search


In my Elastic document i have CityId,RootId,RootName,Price.Now i have to find top 7 roots in a city with following conditions.

Name and id of root which has minimum price in a City.
top 7 roots:- roots those have max number of entry in a City.

for Example :-

CityId RootId RootName Price
11      1       ABC      90
11      1       ABC      100
11      2       DEF      80
11      2       DEF      90
11      2       DEF      60

answer for CityId =11:-

RootId RootName Price
2       DEF      60
1       ABC      90

Solution

  • I am not aware of the syntax of the Nest. Adding a working example in JSON format.

    Index Mapping:

    {
      "mappings":{
        "properties":{
          "listItems":{
            "type":"nested"
          }
        }
      }
    }
    

    Index Data:

    {
        "RootId": 2,
        "CityId": 11,
        "RootName": "DEF",
        "listItems": [
            {
                "Price": 60
            },
            {
                "Price": 90
            },
            {
                "Price": 80
            }
        ]
    }
    {
        "RootId": 1,
        "CityId": 11,
        "RootName": "ABC",
        "listItems": [
            {
                "Price": 100
            },
            {
                "Price": 90
            }
        ]
    }
    

    Search Query:

    {
        "size": 0,
        "aggs": {
            "id_terms": {
                "terms": {
                    "field": "RootId"
                },
                
                "aggs": {
                    "nested_entries": {
                        "nested": {
                            "path": "listItems"
                        },
                        "aggs": {
                            "min_position": {
                                "min": {
                                    "field": "listItems.Price"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    

    Search Result:

    "aggregations": {
        "id_terms": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": 1,
              "doc_count": 1,
              "nested_entries": {
                "doc_count": 2,
                "min_position": {
                  "value": 90.0
                }
              }
            },
            {
              "key": 2,
              "doc_count": 1,
              "nested_entries": {
                "doc_count": 3,
                "min_position": {
                  "value": 60.0
                }
              }
            }
          ]
        }
      }