How to setup/use Java OpenSearch client

Hi,

I’ve tried to use the code from Java high-level REST client - OpenSearch documentation but can’t get it to run correctly.

Does someone have an example I can look at?

I think I have the wrong dependencies

implementation ‘org.opensearch.client:opensearch-rest-high-level-client:1.2.4’
implementation ‘org.apache.httpcomponents:httpclient:4.5.13’

Code

//Establish credentials to use basic authentication.
//Only for demo purposes. Don’t specify your credentials in code.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("username", "password"));

    //Create a client.
    RestClientBuilder builder = RestClient.builder(new HttpHost("endpoint", 9200, "https"))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            });
    RestHighLevelClient client = new RestHighLevelClient(builder);

    //Adding data to the index.
    IndexRequest request = new IndexRequest("custom-index"); //Add a document to the custom-index we created.
    request.id("1"); //Assign an ID to the document.

    HashMap<String, String> stringMapping = new HashMap<String, String>();
    stringMapping.put("message:", log);
    request.source(stringMapping); //Place your content into the index's source.
    IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

Thanks

Hi @java-mcjava ,

AFAIK you are using correct dependencies and RestHighLevelClient is constructed properly. What do you mean by “can’t get it to run correctly”?

Best Regards,
Andriy Redko