一尘不染

Elastic Search 6嵌套查询聚合

elasticsearch

我是elasticsearch查询和聚合的新手。我有一个带有以下映射的嵌套文档

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

我已插入示例数据,如下所示

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"
      }]
     }

我如何为以下内容构建查询DSL

  1. 员工人数最多的部门
  2. 大多数部门的员工

我正在使用Elastic Search 6.2.4


阅读 289

收藏
2020-06-22

共1个答案

一尘不染

您的第一个问题答案是在此链接中嵌套的内部文档数哪个统计信息

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

这回答了您的第二个问题,同时也阅读了链接。

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

阅读嵌套的Agg

我希望这能给您您所需要的。

2020-06-22