# Elasticsearch array only contains query

**URL:** <https://discuss.elastic.co/t/elasticsearch-array-only-contains-query/298666>\
**Category:** Elasticsearch\
**Created:** [March 2, 2022, 7:18pm UTC](https://discuss.elastic.co/t/elasticsearch-array-only-contains-query/298666 "2022-03-02T19:18:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![viswanathk243](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/viswanathk243/32/54736_2.png) [@viswanathk243](https://discuss.elastic.co/u/viswanathk243)\
**Post date:** [March 2, 2022, 7:18pm UTC](https://discuss.elastic.co/t/elasticsearch-array-only-contains-query/298666/1 "2022-03-02T19:18:44Z")

</div>

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

```auto
{
  "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.

---

<div class="post-metadata">

**Author:** ![casterQ](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/casterq/32/93257_2.png) [@casterQ](https://discuss.elastic.co/u/casterQ)\
**Post date:** [March 3, 2022, 3:07am UTC](https://discuss.elastic.co/t/elasticsearch-array-only-contains-query/298666/2 "2022-03-03T03:07:26Z")

</div>

There is a solution：

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

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [March 31, 2022, 3:07am UTC](https://discuss.elastic.co/t/elasticsearch-array-only-contains-query/298666/3 "2022-03-31T03:07:34Z")

</div>

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