Ayush Jain
Ayush Jain

Reputation: 33

AND search in an array of strings Elasticsearch

Let's say I have an array field containing strings in Elasticsearch documents. Let the array in one of the documents be

mArray1: ["string1", "string2", "string3", "string4"]
mArray2: ["string1", "string7", "string11"]

I want a query to search the document which has both "string1" and "string2", i.e. it should return mArray1. Here is what I am using which uses OR filtering.I am also matching for another field which should be compulsory

query: {
    bool: {
      filter: [
        {
          range: {
            "math.score": {
              gte: 80
            }
          }
        },
        {
          multi_match: {
            query: "name1",
            fields: ["name", "full_name"],
            type: "phrase_prefix"
          }
        }
      ],
      must: [
        {
          terms: {
            "arrayField": ["string1", "string2"]
          }
        }
      ]
    }
  }

Upvotes: 1

Views: 41

Answers (1)

khachik
khachik

Reputation: 28693

terms matches any of the values specified, you want to match documents that have both string1 and string2 to, then you need to two term queries in must:

"must" : [
    {
        "term" : {
            "arrayField" : "string1"
        }
    },
    {
        "term" : {
            "arrayField" : "string2"
        }
    }
]

Upvotes: 0

Related Questions