OpeanSearch query where any of the values should match

When we want to query data in OpenSearch where any one of the values of the given field should match.

In that case, we can use the boolean query that comes with the should option. Should query takes an array of match queries and returns the documents that have any one of them present.

{
    "query": {
        "bool": {
            "should": [
                {"match": {"field1": "value1"}},
                {"match": {"field2": "value2"}},
            ]
        }
    }
}

If the documents don’t have any of the above fields in them then it will return all the documents.

In case we want at least one of them to match we can use a minimum_should_match flag that is provided and pass the number of queries that should match in the returning document.

We can set it to one to at least match one of them.

{
    "query": {
        "bool": {
            "should": [
                {"match": {"field1": "value1"}},
                {"match": {"field2": "value2"}},
            ],
            "minimum_should_match": 1
        }
    }
}

This same query can be performed through Java by creating a list of the queries and then passing it to a boolean query that they should match.

We can also set the minimum_should_match as per our requirement. It is completely optional though.

//create multiple queries
MatchQuery matchQuery1 = new MatchQuery.Builder().field("field1").query("value1").build();
MatchQuery matchQuery2 = new MatchQuery.Builder().field("field2").query("value2").build();

// create a list of queries
List<Query> shouldQueries = new ArrayList<>();
shouldQueries.add(matchQuery1._toQuery());
shouldQueries.add(matchQuery2._toQuery());

// pass the list to boolean query for each query to must not match
BoolQuery boolQuery = new BoolQuery.Builder().should(shouldQueries).minimumShouldMatch("1").build();

// perform the search
SearchResponse<Object> searchResponse = client.search(s -> {
    s.query(boolQuery._toQuery());
    return s;
}, Object.class);

// store the result
List<Object> output = new ArrayList<>();
for (int i = 0; i < searchResponse.hits().hits().size(); i++) {
    output.add(searchResponse.hits().hits().get(i).source());
}