Java client

The OpenSearch Java client allows you to interact with your OpenSearch clusters through Java methods and data structures rather than HTTP methods and raw JSON. For example, you can submit requests to your cluster using objects to create indexes, add data to documents, or complete some other operation using the client’s built-in methods. For the client’s complete API documentation and additional examples, see the javadoc.

This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the opensearch-java repo.

Installing the client using Apache HttpClient 5 Transport

To start using the OpenSearch Java client, you need to provide a transport. The default ApacheHttpClient5TransportBuilder transport comes with the Java client. To use the OpenSearch Java client with the default transport, add it to your pom.xml file as a dependency:

  1. <dependency>
  2. <groupId>org.opensearch.client</groupId>
  3. <artifactId>opensearch-java</artifactId>
  4. <version>2.6.0</version>
  5. </dependency>

copy

If you’re using Gradle, add the following dependencies to your project:

  1. dependencies {
  2. implementation 'org.opensearch.client:opensearch-java:2.6.0'
  3. }

copy

You can now start your OpenSearch cluster.

Installing the client using RestClient Transport

Alternatively, you can create a Java client by using the RestClient-based transport. In this case, make sure that you have the following dependencies in your project’s pom.xml file:

  1. <dependency>
  2. <groupId>org.opensearch.client</groupId>
  3. <artifactId>opensearch-rest-client</artifactId>
  4. <version>2.9.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.opensearch.client</groupId>
  8. <artifactId>opensearch-java</artifactId>
  9. <version>2.6.0</version>
  10. </dependency>

copy

If you’re using Gradle, add the following dependencies to your project”

  1. dependencies {
  2. implementation 'org.opensearch.client:opensearch-rest-client:2.9.0'
  3. implementation 'org.opensearch.client:opensearch-java:2.6.0'
  4. }

copy

You can now start your OpenSearch cluster.

Security

Before using the REST client in your Java application, you must configure the application’s truststore to connect to the Security plugin. If you are using self-signed certificates or demo configurations, you can use the following command to create a custom truststore and add in root authority certificates.

If you’re using certificates from a trusted Certificate Authority (CA), you don’t need to configure the truststore.

  1. keytool -import <path-to-cert> -alias <alias-to-call-cert> -keystore <truststore-name>

copy

You can now point your Java client to the truststore and set basic authentication credentials that can access a secure cluster (refer to the sample code below on how to do so).

If you run into issues when configuring security, see common issues and troubleshoot TLS.

Sample data

This section uses a class called IndexData, which is a simple Java class that stores basic data and methods. For your own OpenSearch cluster, you might find that you need a more robust class to store your data.

IndexData class

  1. static class IndexData {
  2. private String firstName;
  3. private String lastName;
  4. public IndexData(String firstName, String lastName) {
  5. this.firstName = firstName;
  6. this.lastName = lastName;
  7. }
  8. public String getFirstName() {
  9. return firstName;
  10. }
  11. public void setFirstName(String firstName) {
  12. this.firstName = firstName;
  13. }
  14. public String getLastName() {
  15. return lastName;
  16. }
  17. public void setLastName(String lastName) {
  18. this.lastName = lastName;
  19. }
  20. @Override
  21. public String toString() {
  22. return String.format("IndexData{first name='%s', last name='%s'}", firstName, lastName);
  23. }
  24. }

copy

Initializing the client with SSL and TLS enabled using Apache HttpClient 5 Transport

This code example uses basic credentials that come with the default OpenSearch configuration. If you’re using the Java client with your own OpenSearch cluster, be sure to change the code so that it uses your own credentials.

The following sample code initializes a client with SSL and TLS enabled:

  1. import javax.net.ssl.SSLContext;
  2. import javax.net.ssl.SSLEngine;
  3. import org.apache.hc.client5.http.auth.AuthScope;
  4. import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
  5. import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
  6. import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
  7. import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
  8. import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
  9. import org.apache.hc.core5.function.Factory;
  10. import org.apache.hc.core5.http.HttpHost;
  11. import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
  12. import org.apache.hc.core5.reactor.ssl.TlsDetails;
  13. import org.apache.hc.core5.ssl.SSLContextBuilder;
  14. import org.opensearch.client.opensearch.OpenSearchClient;
  15. import org.opensearch.client.transport.OpenSearchTransport;
  16. import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder;
  17. public class OpenSearchClientExample {
  18. public static void main(String[] args) throws Exception {
  19. System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore");
  20. System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore");
  21. final HttpHost host = new HttpHost("https", "localhost", 9200);
  22. final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  23. // Only for demo purposes. Don't specify your credentials in code.
  24. credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "admin".toCharArray()));
  25. final SSLContext sslcontext = SSLContextBuilder
  26. .create()
  27. .loadTrustMaterial(null, (chains, authType) -> true)
  28. .build();
  29. final ApacheHttpClient5TransportBuilder builder = ApacheHttpClient5TransportBuilder.builder(host);
  30. builder.setHttpClientConfigCallback(httpClientBuilder -> {
  31. final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
  32. .setSslContext(SSLContextBuilder.create().build())
  33. // See https://issues.apache.org/jira/browse/HTTPCLIENT-2219
  34. .setTlsDetailsFactory(new Factory<SSLEngine, TlsDetails>() {
  35. @Override
  36. public TlsDetails create(final SSLEngine sslEngine) {
  37. return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol());
  38. }
  39. })
  40. .build();
  41. final PoolingAsyncClientConnectionManager connectionManager = PoolingAsyncClientConnectionManagerBuilder
  42. .create()
  43. .setTlsStrategy(tlsStrategy)
  44. .build();
  45. return httpClientBuilder
  46. .setDefaultCredentialsProvider(credentialsProvider)
  47. .setConnectionManager(connectionManager);
  48. });
  49. final OpenSearchTransport transport = ApacheHttpClient5TransportBuilder.builder(host).build();
  50. OpenSearchClient client = new OpenSearchClient(transport);
  51. }
  52. }

Initializing the client with SSL and TLS enabled using RestClient Transport

This code example uses basic credentials that come with the default OpenSearch configuration. If you’re using the Java client with your own OpenSearch cluster, be sure to change the code so that it uses your own credentials.

The following sample code initializes a client with SSL and TLS enabled:

  1. import org.apache.http.HttpHost;
  2. import org.apache.http.auth.AuthScope;
  3. import org.apache.http.auth.UsernamePasswordCredentials;
  4. import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
  5. import org.apache.http.impl.client.BasicCredentialsProvider;
  6. import org.opensearch.client.RestClient;
  7. import org.opensearch.client.RestClientBuilder;
  8. import org.opensearch.client.json.jackson.JacksonJsonpMapper;
  9. import org.opensearch.client.opensearch.OpenSearchClient;
  10. import org.opensearch.client.transport.OpenSearchTransport;
  11. import org.opensearch.client.transport.rest_client.RestClientTransport;
  12. public class OpenSearchClientExample {
  13. public static void main(String[] args) throws Exception {
  14. System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore");
  15. System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore");
  16. final HttpHost host = new HttpHost("https", 9200, "localhost");
  17. final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  18. //Only for demo purposes. Don't specify your credentials in code.
  19. credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials("admin", "admin"));
  20. //Initialize the client with SSL and TLS enabled
  21. final RestClient restClient = RestClient.builder(host).
  22. setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
  23. @Override
  24. public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
  25. return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  26. }
  27. }).build();
  28. final OpenSearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  29. final OpenSearchClient client = new OpenSearchClient(transport);
  30. }
  31. }

copy

Connecting to Amazon OpenSearch Service

The following example illustrates connecting to Amazon OpenSearch Service:

  1. SdkHttpClient httpClient = ApacheHttpClient.builder().build();
  2. OpenSearchClient client = new OpenSearchClient(
  3. new AwsSdk2Transport(
  4. httpClient,
  5. "search-...us-west-2.es.amazonaws.com", // OpenSearch endpoint, without https://
  6. "es"
  7. Region.US_WEST_2, // signing service region
  8. AwsSdk2TransportOptions.builder().build()
  9. )
  10. );
  11. InfoResponse info = client.info();
  12. System.out.println(info.version().distribution() + ": " + info.version().number());
  13. httpClient.close();

copy

Connecting to Amazon OpenSearch Serverless

The following example illustrates connecting to Amazon OpenSearch Serverless Service:

  1. SdkHttpClient httpClient = ApacheHttpClient.builder().build();
  2. OpenSearchClient client = new OpenSearchClient(
  3. new AwsSdk2Transport(
  4. httpClient,
  5. "search-...us-west-2.aoss.amazonaws.com", // OpenSearch endpoint, without https://
  6. "aoss"
  7. Region.US_WEST_2, // signing service region
  8. AwsSdk2TransportOptions.builder().build()
  9. )
  10. );
  11. InfoResponse info = client.info();
  12. System.out.println(info.version().distribution() + ": " + info.version().number());
  13. httpClient.close();

copy

Creating an index

You can create an index with non-default settings using the following code:

  1. String index = "sample-index";
  2. CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build();
  3. client.indices().create(createIndexRequest);
  4. IndexSettings indexSettings = new IndexSettings.Builder().autoExpandReplicas("0-all").build();
  5. IndexSettingsBody settingsBody = new IndexSettingsBody.Builder().settings(indexSettings).build();
  6. PutSettingsRequest putSettingsRequest = new PutSettingsRequest.Builder().index(index).value(settingsBody).build();
  7. client.indices().putSettings(putSettingsRequest);

copy

Indexing data

You can index data into OpenSearch using the following code:

  1. IndexData indexData = new IndexData("first_name", "Bruce");
  2. IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").document(indexData).build();
  3. client.index(indexRequest);

copy

Searching for documents

You can search for a document using the following code:

  1. SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
  2. for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
  3. System.out.println(searchResponse.hits().hits().get(i).source());
  4. }

copy

Deleting a document

The following sample code deletes a document whose ID is 1:

  1. client.delete(b -> b.index(index).id("1"));

copy

Deleting an index

The following sample code deletes an index:

  1. DeleteIndexRequest deleteIndexRequest = new DeleteRequest.Builder().index(index).build();
  2. DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);

copy

Sample program

The following sample program creates a client, adds an index with non-default settings, inserts a document, searches for the document, deletes the document, and then deletes the index:

  1. import org.apache.http.HttpHost;
  2. import org.apache.http.auth.AuthScope;
  3. import org.apache.http.auth.UsernamePasswordCredentials;
  4. import org.apache.http.client.CredentialsProvider;
  5. import org.apache.http.impl.client.BasicCredentialsProvider;
  6. import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
  7. import org.opensearch.client.RestClient;
  8. import org.opensearch.client.RestClientBuilder;
  9. import org.opensearch.client.base.RestClientTransport;
  10. import org.opensearch.client.base.Transport;
  11. import org.opensearch.client.json.jackson.JacksonJsonpMapper;
  12. import org.opensearch.client.opensearch.OpenSearchClient;
  13. import org.opensearch.client.opensearch._global.IndexRequest;
  14. import org.opensearch.client.opensearch._global.IndexResponse;
  15. import org.opensearch.client.opensearch._global.SearchResponse;
  16. import org.opensearch.client.opensearch.indices.*;
  17. import org.opensearch.client.opensearch.indices.put_settings.IndexSettingsBody;
  18. import java.io.IOException;
  19. public class OpenSearchClientExample {
  20. public static void main(String[] args) {
  21. RestClient restClient = null;
  22. try{
  23. System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore");
  24. System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore");
  25. //Only for demo purposes. Don't specify your credentials in code.
  26. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  27. credentialsProvider.setCredentials(AuthScope.ANY,
  28. new UsernamePasswordCredentials("admin", "admin"));
  29. //Initialize the client with SSL and TLS enabled
  30. restClient = RestClient.builder(new HttpHost("localhost", 9200, "https")).
  31. setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
  32. @Override
  33. public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
  34. return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  35. }
  36. }).build();
  37. Transport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  38. OpenSearchClient client = new OpenSearchClient(transport);
  39. //Create the index
  40. String index = "sample-index";
  41. CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build();
  42. client.indices().create(createIndexRequest);
  43. //Add some settings to the index
  44. IndexSettings indexSettings = new IndexSettings.Builder().autoExpandReplicas("0-all").build();
  45. IndexSettingsBody settingsBody = new IndexSettingsBody.Builder().settings(indexSettings).build();
  46. PutSettingsRequest putSettingsRequest = new PutSettingsRequest.Builder().index(index).value(settingsBody).build();
  47. client.indices().putSettings(putSettingsRequest);
  48. //Index some data
  49. IndexData indexData = new IndexData("first_name", "Bruce");
  50. IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").document(indexData).build();
  51. client.index(indexRequest);
  52. //Search for the document
  53. SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
  54. for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
  55. System.out.println(searchResponse.hits().hits().get(i).source());
  56. }
  57. //Delete the document
  58. client.delete(b -> b.index(index).id("1"));
  59. // Delete the index
  60. DeleteIndexRequest deleteIndexRequest = new DeleteRequest.Builder().index(index).build();
  61. DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);
  62. } catch (IOException e){
  63. System.out.println(e.toString());
  64. } finally {
  65. try {
  66. if (restClient != null) {
  67. restClient.close();
  68. }
  69. } catch (IOException e) {
  70. System.out.println(e.toString());
  71. }
  72. }
  73. }
  74. }

copy