Jayaram
Jayaram

Reputation: 6606

Multiple (AND) queries for a nested index structure in Elasticsearch

I have an index with the below mapping

{
  "mappings": {
    "xxxxx": {
      "properties": {
        "ID": {
          "type": "text"
        },
        "pairs": {
          "type": "nested"
        },
        "xxxxx": {
          "type": "text"
        }
      }
    }
  }
}

the pairs field is essentially an array of objects - each object has a unique ID associated with it

What i'm trying to do is to get only one object from the pairs field for updates. To that extent , i've tried this

GET /sample/_search/?size=1000
{
    "query": {
      "bool": {
        "must": [
            {
              "match": {
                "ID": "2rXdCf5OM9g1ebPNFdZNqW"
              }
            },
            {
              "match": {
                "pairs.id": "c1vNGnnQLuk"
              }
            }
          ]
      }
  },
  "_source": "pairs"
}

but this just returns an empty object despite them being valid IDs. If i remove the pairs.id rule - i get the entire array of objects .

What do i need to add/edit to ensure that i can query via both IDS (original and nested)

Upvotes: 0

Views: 48

Answers (1)

Val
Val

Reputation: 217344

Since pairs is of nested type, you need to use a nested query. Also you might probably want to leverage nested inner-hits as well:

GET /sample/_search/?size=1000
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "ID": "2rXdCf5OM9g1ebPNFdZNqW"
          }
        },
        {
          "nested": {
            "path": "pairs",
            "query": {
              "match": {
                "pairs.id": "c1vNGnnQLuk"
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  },
  "_source": false
}

Upvotes: 1

Related Questions