When we want to query OpenSearch with multiple values in the same field or different fields and want our result to match all of those, we can use the following query.
It has a boolean query that must match the field that accepts an array of values that you want to match. We can pass the multiple field values to that.
{ "query": { "bool": { "must": [ {"match": {"field1": "value1"}}, {"match": {"field2": "value2"}}, ] } } }
This will return the search results for the documents that have both fields with the given value.
We can create this same query in Java client using the boolean query.
All we have to do is convert the above JSON query to Java and for the same, we will create a list of match queries and then pass the list to a boolean query for must matching.
//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 ListmustQueries = new ArrayList<>(); mustQueries.add(matchQuery1._toQuery()); mustQueries.add(matchQuery2._toQuery()); // pass the list to boolean query for each query to must match BoolQuery boolQuery = new BoolQuery.Builder().must(mustQueries).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()); }
This will return the list of matching documents.