Dennis
Dennis

Reputation: 1951

ElasticSearch - query documents: All given labels appear at least one time in a nested document

Consider a few indexed documents (employees) containing nested documents (skills) with one property, let's say "label", so that each employee is associated with a few skills. I would like to fetch all employees (documents) from the ElasticSearch index, who master a given set of skills, for example "Python" and "Java".

I am struggling to find a suitable query to ensure that all given skills ("Python", "Java") appear at least once in the set of skills of an employee, although they do not have to appear together!

My mapping is similar to this one:

{
  "mappings": {
    "employee": {
      "_all": { "enabled": false },
      "properties": {
        "id" : { "type": "integer" },
        "first_name" : { "type": "string" },
        "last_name" : { "type": "string" },

        "skills": {
          "type": "nested",
          "properties": {
            "label": { "type": "string" },
            "rating": { "type": "integer" }
          }
        }

      }
    }
  }
} 

So I am looking for any solutions (queries) on how to retrieve the desired results.

Upvotes: 0

Views: 322

Answers (1)

Val
Val

Reputation: 217424

You need to use two nested filters combined in a bool/filter query, like this:

POST /employees/employee/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "nested": {
            "path": "skills",
            "query": {
              "term": {
                "skills.label": "python"
              }
            }
          }
        },
        {
          "nested": {
            "path": "skills",
            "query": {
              "term": {
                "skills.label": "java"
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions