1

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"]
          }
        }
      ]
    }
  }

1 Answer 1

0

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"
        }
    }
]
Sign up to request clarification or add additional context in comments.

2 Comments

But there's no way to specify the order of elements so it matches ["string1", "string2", "string3", "string4"] but not ["string2", "string1", "string3", "string4"] ?
There is no way to do it in ES, unless you use scripted queries (which come with their own problems like performance/scaling).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.