简体   繁体   中英

Elasticsearch query filter by unique field

Using Elasticsearch, I have employees mapped, each employee belonging to some team. Every team should have a team leader and I need to validate that. Is there a way to search for every team on its own, but in one query, to verify it has an employee with the field "is_leader": true? I would like to get results of all teams lacking a team 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,
},
}

You can use a terms aggregation on the team field to separate all teams, and then use another terms sub-aggregation on the is_leader field. That way you'll get the count for leader vs not-leader for each team. The teams with 0 leader will stand out:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM