Elasticsearch array only contains query

Let's say I've data in this format:

{
  "id": "doc0",
  "tags": ["a", "b", "c"]
}

{
  "id": "doc1",
  "tags": ["a", "b", "c", "d"]
}

{
  "id": "doc2",
  "tags": ["a", "b"]
}

I need to form an ES query that fetches only documents that contains both "a", "b" and nothing else.

If I write a terms query, it matches all the documents, as all documents have both "a" and "b" but only one document has nothing else apart from "a" and "b"

What is the best way to form this query? I don't have the list of the other values to add "not_contains" clause.

There is a solution:

POST index/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "script": {
            "script": """
              return  doc['tags'].size() == 2;
            """
          }
        },
        {
          "term": {
            "tags": {
              "value": "a"
            }
          }
        }
      ]
    }
  }
}

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