How to perform an exact match of field when each field is within a list in Elasticsearch

  elasticsearch, elasticsearch-dsl-py, python-3.x

Sample of the data present in my ES index :

{
  "entities" : [
    {
      "fieldName" : "abc"
    },
    {
      "fieldName" : "def"
    }
  ], 
  "entities" : [
    {
      "fieldName" : "abc"
    },
    {
      "fieldName" : "def"
    }
  ],
 "entities" : [
    {
      "fieldName" : "abc"
    },
    {
      "fieldName" : "def"
    },
    {
      "fieldName" : "gh"
    }
  ]
}

I would like to find only those documents where the fieldName only matches "abc" and "def", so I have tried a nested match query of ES but the problem is it is also matching documents having extra fields apart from "abc" and "def".

GET fetch_latest_version/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "entities",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "entities.fieldName": "abc"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "entities",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "entities.fieldName": "def"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }

The result of the above query is it will list all the 3 documents present in sample data. I would only want it to match the 1st and 2nd document only(like an exact match) where entities list has only "abc" and "def" fields. I shouldn’t match the 3rd document where fieldName are ("abc","def","gh") .

Source: Python-3x Questions

LEAVE A COMMENT