OpeanSearch query where the values must not match

There are times when we want to query data in which fields with certain values should not be present in the document.

OpenSearch has a boolean query in which there is an option where we can search with values that must not match.

Following is the JSON structure for the same.

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

We can run the same query with the following implementation in Java.

All we have to do is create a match query with the field name and its value and then pass it to the boolean query to must not match.

This will return the result with the documents that do not contain the above field and value pair.

//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> mustNotQueries = new ArrayList<>();
mustNotQueries.add(matchQuery1._toQuery());
mustNotQueries.add(matchQuery2._toQuery());

// pass the list to a boolean query for each query to must not match
BoolQuery boolQuery = new BoolQuery.Builder().mustNot(mustNotQueries).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());
}