How to connect to the OpenSearch via Java client

OpenSearch provides a Java SDK that makes it extremely simple to interact with it.

Make sure these two packages are installed in your Java application.

implementation 'org.opensearch.client:opensearch-java:1.0.0'
implementation 'org.opensearch.client:opensearch-rest-client:1.3.4'

To connect with OpenSearch we need to have the URL of the application and username and password.

The URL has to be broken down into three different parts

  • Host – Base URL of the OpenSearch for example localhost.
  • Protocol – HTTPS or HTTP.
  • Port – 9200 default port for OpenSearch.

These three properties have to pass individually to the RestClientBuilder provided by OpenSearch.

public class OpenSearch{
    private OpenSearchClient client = null;
    private RestClient restClient = null;

    public boolean init(String host, int port, String protocol, String username, String password) {
        try{
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));

            restClient = RestClient.builder(new HttpHost(host, port, protocol)).
                    setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    }).build();
            Transport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

            client = new OpenSearchClient((OpenSearchTransport) transport);

            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (restClient != null) {
                restClient.close();
                client.shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The initialization and closing of the client have been separated into two different methods and you use them according to your need.

OpenSearch os = new OpenSearch();

// default credential for local
Boolean initialized = os.init('localhost', 9200, 'http', 'admin', 'admin');

// to close the connection
os.close();