[Recipes] Elasticsearch Aggregation for Nested Objects

Problem: 

Do aggregations over nested objects.

Solution Summary: 

Neste objects needs to be aggregated using "nested" element, a special single bucket aggregation that enables aggregating nested documents. You can find why we need nested objects at following link and then see how we create nested objects on the link here.

Prerequisites: 

Setup department mapping and then add department documents as described here. The "employees" is a nested array within department. 

Solution Steps: 

Case 1 - Find average employee age across departments

GET department/_search 
{
  "aggs": {
    "employees": {
      "nested": {
        "path": "employees"
      },
      "aggs": {
        "average_age": {
          "avg": {
            "field": "employees.age"
          }
        }
      }
    }
  },
  "size": 0
}

 

Response contains:

...

"hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "employees": {
      "doc_count": 4,
      "average_age": {
        "value": 31.75
      }
    }
  }
}

Learn Serverless from Serverless Programming Cookbook

Contact

Please first use the contact form or facebook page messaging to connect.

Offline Contact
We currently connect locally for discussions and sessions at Bangalore, India. Please follow us on our facebook page for details.
WhatsApp (Primary): (+91) 7411174113
Phone (Escalations): (+91) 7411174114

Business newsletter

Complete the form below, and we'll send you an e-mail every now and again with all the latest news.

About

CloudMaterials is my blog to share notes and learning materials on Cloud and Data Analytics. My current focus is on Microsoft Azure and Amazon Web Services (AWS).

I like to write and I try to document what I learn to share with others. I believe that knowledge is useless unless you share it; the more you share, the more you learn.

Recent comments

Photo Stream