弹性搜索6嵌套查询聚合

时间:2018-05-12 18:04:33

标签: elasticsearch querydsl

我是弹性搜索查询和聚合的新手。 我有一个嵌套文档,其中包含以下映射

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. 大多数部门的员工
  3. 我正在使用Elastic Search 6.2.4

1 个答案:

答案 0 :(得分:1)

您的第一个问题答案在此链接中nested inner doc count哪些统计信息

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

Read Nested Agg

我希望这可以满足您的需求。