Elasticsearch查询按唯一字段筛选

时间:2017-07-19 13:44:24

标签: elasticsearch

使用Elasticsearch,我有员工映射,每个员工都属于某个团队。每个团队都应该有一个团队领导,我需要验证这一点。有没有办法自己搜索每个团队,但在一个查询中,要验证它是否有一个有字段的员工" is_leader":是吗?我希望得到所有团队缺乏团队领导的结果。

{
{
            "_type": "employee",
            "name": "Jade",
            "team": "A",
            "is_leader": false,
},
{
            "_type": "employee",
            "name": "Jack",
            "team": "A",
            "is_leader": false,
},
{           "_type": "employee",
            "name": "Sarah",
            "team": "A",
            "is_leader": true,
},
{           "_type": "employee",
            "name": "Jim",
            "team": "B",
            "is_leader": false,
},
{           "_type": "employee",
            "name": "Don",
            "team": "B",
            "is_leader": false,
},
{           "_type": "employee",
            "name": "Jess",
            "team": "B",
            "is_leader": false,
},
}

1 个答案:

答案 0 :(得分:0)

您可以在terms字段上使用team聚合来分隔所有团队,然后在terms字段上使用另一个is_leader子聚合。通过这种方式,您可以获得每个团队的领导者与非领导者的计数。拥有0名领导者的球队将脱颖而出:

{
  "size": 0,
  "aggs": {
    "teams": {
      "terms": {
        "field": "team"
      },
      "aggs": {
        "leaders": {
          "terms": {
            "field": "is_leader"
          }
        }
      }
    }
  }
}