arunimsamat
arunimsamat

Reputation: 29

ElasticSearch Nested Query formulation

I have a mapping like this

{
    "experience": {
        "type": "nested",
        "properties": {
            "end": {
                "type": "string"
            },
            "organization": {
                "type": "nested",
                "properties": {
                    "details": {
                        "type": "string"
                    },
                    "name": {
                        "type": "string"
                    }
                }
            }
        }
    }
}

Now I want to make a query like this:

{
  "nested": {
    "path": "experience",
    "query": {
      "bool": {
        "must": [{
          "match": {
            "experience.organization.name": {
              "query": company_name,
              "operator": "and"
            }
          }
        }, {
          "match": {
            "experience.end": "Present"
          }
        }]
      }
    }
  }
}

The above query is not returning any results, is this the correct way to index and query the above scenario?

I am confused about what should be the value of the path variable since organisation.name and end are not at the same level.

Upvotes: 0

Views: 73

Answers (1)

jhilden
jhilden

Reputation: 12419

Here is a complete working sample with your code:

PUT index1/test1/_mapping
{
  "test1": {
    "properties": {
      "experience": {
        "type": "nested",
        "properties": {
          "end": {
            "type": "string"
          },
          "organization": {
            "type": "nested",
            "properties": {
              "details": {
                "type": "string"
              },
              "name": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  }
}

POST index1/test1
{
  "experience": {
    "end": "Present",
    "organization": {
      "name": "org1",
      "details": "some details here"
    }
  }
}

GET index1/test1/_search
{
  "query": {
    "nested": {
      "path": "experience",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "end": "present"
              }
            },
            {
              "nested": {
                "path": "experience.organization",
                "query": {
                  "match": {
                    "name": "org1"
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

That being said, you have a double nested object here which you will probably find will work against you in the long run. I would consider flattening the data so that the nested is not necessary.

Upvotes: 1

Related Questions