OpenSearch search for key with a given value via java client

Learn how to search documents with a given key value from a specified index in OpenSearch via a java client.

OpenSearch has provided a Java SDK that makes it extremely simple to communicate with it through any java application.

To find documents in which a field has a specific value, we can use the match query.

Java SDK has a MatchQuery builder that helps to create a query and then pass it for searching.

 MatchQuery matchQuery = new MatchQuery.Builder().field("field-name").query(FieldValue.of("feild-value")).build();
 SearchResponse<Object> searchResponse2 = openSearchClient.search(s -> {
    s.index("sample-index");
    s.query(matchQuery._toQuery());
    return s;
}, Object.class);

This will return a list of documents that has the given key-value pair.