syv
syv

Reputation: 3608

Elasticsearch Nested object Search with AND Condition

Here is my data in Elasticsearch - I kept Tags as nested object

PUT myblog/3
{
  "id" : 10003,
  "tags" : [ 
    {
      "tag" : 45647
    },
    {
    "tag" : 45648
    }
  ]
}


PUT myblog/4
{
  "id" : 10004,
  "tags" : [ 
    {
      "tag" : 45647
    }
  ]
}

PUT myblog/5
{
  "id" : 10005,
  "tags" : [ 
    {
    "tag" : 45648
    }
  ]
}

I want to retrieve documents with tag is 45647 & 45648. I tried it in this way

GET myblog/_search
{

  "query": {
    "nested": {
      "path": "tags",
      "query": {
        "bool": {
          "must": [
            { "match": { "tags.tag": 45648}}, 
            { "match": { "tags.tag": 45647}}
          ]
        }
      }
    }
  }
}

But it is not returning the expected result. What is missing in my query to get expected result?

Upvotes: 0

Views: 30

Answers (1)

Val
Val

Reputation: 217254

You're almost there. You need two nested clauses since each nested element is a different document underneath. Try like this:

GET myblog/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "tags",
            "query": {
              "match": {
                "tags.tag": 45648
              }
            }
          }
        },
        {
          "nested": {
            "path": "tags",
            "query": {
              "match": {
                "tags.tag": 45647
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions