user2475467
user2475467

Reputation: 129

Querying a field having nested objects in Elasticsearch

I have a type called jobdetails. The type contain professional experience related details of employees. Each employee document have an experience filed which is type nested.

"experience": 
    {

        "type": "nested",
        "properties": 
        {
            "company": {
                "type": "string"
                   },
            "title":{
                "type": "string"
                    }
        }
    }

I would like to know how to fetch employees having only “manager” or “teacher” but not “trainee” experience in their experience field.

For Ex:

doc 1: experience[
{“company”:“xxx”, “title”:”manager”}, 
{“company”:“xxx”, “title”:”teacher”}, 
{“company”:“xxx”, “title”:”trainee manager”},]

doc 2: experience[{“company”:“xxx”, “title”:”manager”}]

doc 3: experience[{“company”:“xxx”, “title”:”teacher”}]

doc 4: experience[
{“company”:“xxx”, “title”:”manager”},
{“company”:“xxx”, “title”:”teacher]

The required query should return doc2, doc3, doc4 but not doc1.

Upvotes: 0

Views: 64

Answers (1)

Val
Val

Reputation: 217254

A query like the following one should do the trick, i.e. we're looking for documents whose experience.title field contains either manager or teacher but not trainee

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "nested": {
                "path": "experience",
                "filter": {
                  "terms": {
                    "experience.title": [
                      "manager",
                      "teacher"
                    ]
                  }
                }
              }
            }
          ],
          "must_not": [
            {
              "nested": {
                "path": "experience",
                "filter": {
                  "terms": {
                    "experience.title": [
                      "trainee"
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 1

Related Questions