Search code examples
elasticsearchquerydsl

Elastic Search 6 Nested Query Aggregations


i am new to elastic search Query and aggregation. I have a nested document with the following mapping

PUT /company
{
 "mappings": {
 `"data": {
  "properties": {
    "deptId": {
      "type": "keyword"
    },
     "deptName": {
      "type": "keyword"
    },
    "employee": {
      "type": "nested",
      "properties": {
        "empId": {
          "type": "keyword"
        },
        "empName": {
          "type": "text"
        },
        "salary": {
          "type": "float"
        }
       }}}}}}

I have inserted Sample Data as follows

PUT company/data/1
{
"deptId":"1",
"deptName":"HR",
 "employee": [
  {
    "empId": "1",
    "empName": "John",
    "salary":"1000"
  },
   {
    "empId": "2",
    "empName": "Will",
    "salary":"2000"
  }
 ]}

PUT company/data/3
{
  "deptId":"3",
  "deptName":"FINANCE",
   "employee": [
      {
        "empId": "1",
        "empName": "John",
        "salary":"1000"
      },
       {
        "empId": "2",
        "empName": "Will",
        "salary":"2000"
      },
       {
        "empId": "3",
        "empName": "Mark",
        "salary":"4000"
      }]
     }

How can i Construct a Query DSL for the following

  1. Department with the maximum Employees
  2. Employee that is present in most departments

I am using Elastic Search 6.2.4


Solution

  • Your First Questions answer is in this link nested inner doc count Which Stats

    POST test/_search
    {
      "query": {
        "nested": {
          "path": "employee",
          "inner_hits": {} 
        }
      }
    }
    

    This Answers your Second Question there is also reading the link attached.

    GET /my_index/blogpost/_search
    {
      "size" : 0,
      "aggs": {
        "employee": { 
          "nested": {
            "path": "employee"
          },
          "aggs": {
            "by_name": {
              "terms": { 
                "field":    "employee.empName"
              }
            }
          }
        }
      }
    }
    

    Read Nested Agg

    I hope this gives you what you need.