How to loop through the values of array list to exactly match all the values

Consider the below documents:

Documents

Doc 1

{
    "id": [
        "1a",
        "1b",
        "1c"
    ]
}

Doc 2

{
    "id": [
        "1a",
        "1b"
    ]
}

Doc 3

{
    "id": [
        "1a"
    ]
}

Now if I search

For "id" : ["1a","1b"], then only doc 2 should match

For "id" : ["1a","1b","1d"], no documents should match

For "id" : ["1a"] only document 3 should match

It is similar to the below java code implementation

import java.util.*;
  
class Test {
    public static void main(String[] args)
    {
        List<String> list1 = Arrays.asList("One", "Two");
        List<String> list2 = Arrays.asList("One","Two","Three");
        boolean isMatch = list2.equals(list1);
        System.out.println(isMatch);
    }
}

With terms query and a query string, I attempted to build the above use case scenario, but it does not function for an exact match.

So, I think the best way should be to use the script, where I can loop through the values of the array list OR use equals from Shared API to achieve this use case.

Can anyone please help me with the script for this?

Have you looked at the terms set query? If youindex the length of the array and add a condition for this you may be able to achieve what you describe.

1 Like

@Christian_Dahlqvist yes, I tried with terms set query also, but I didn't solve all the use case scenarios.

What case did it not solve? Based on your example it seems like a great fit.

yes @Christian_Dahlqvist, I tried again using the minimum_should_match_script param, and all the cases are covered. But, there is one more issue, I cannot add one more field in each document (which is required in the terms set query) to find the match count.

Is there any way, to do this without adding any extra fields to the documents?

You can probably add a runtime field to calculate the length of the array and make this available as a field, but that will be slower than indexing it.