Search for documents containing an item not present in a list

I have indexed documents that contain a field name with a string value:

[
    {
        "fruits": [
            {
                "name": "apple",
                "color": "red"
            },
            {
                "name": "banana",
                "color": "yellow"
            }
        ]
    },
    {
        "fruits": [
            {
                "name": "grape",
                "color": "purple"
            },
            {
                "name": "orange",
                "color": "orange"
            },
            {
                "name": "pear",
                "color": "green"
            }
        ]
    }
]

I have a list of strings in my code:

["apple", "pineapple", "grape", "orange", "pear"]

I want to search for documents that contain a value in the field name that is not present in that list. In this case only the first document would be the result as "banana" is missing.

How can I do that?

Thanks

Hi @Adrian_Fresco

I adapted the query by this post. Try please.

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "fruits",
            "query": {
              "bool": {
                "must_not": [
                  {
                    "terms": {
                      "fruits.name": [
                        "apple",
                        "pineapple",
                        "grape",
                        "orange",
                        "pear"
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
1 Like

Thank you for your answer @RabBit_BR
Is there a way of achieving the result without using nested field mappings?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.