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

To start using the OpenSearch Java client, ensure 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.6.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.opensearch.client</groupId>
  8. <artifactId>opensearch-java</artifactId>
  9. <version>2.0.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.6.0'
  3. implementation 'org.opensearch.client:opensearch-java:2.0.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

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.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. }
  40. }
  41. }

copy

Creating an index

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

  1. String index = "sample-index";
  2. CreateRequest createIndexRequest = new CreateRequest.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. DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).build();
  2. DeleteResponse deleteResponse = client.indices().delete(deleteRequest);
  3. } catch (IOException e){
  4. System.out.println(e.toString());
  5. } finally {
  6. try {
  7. if (restClient != null) {
  8. restClient.close();
  9. }
  10. } catch (IOException e) {
  11. System.out.println(e.toString());
  12. }
  13. }
  14. }
  15. }

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. CreateRequest createIndexRequest = new CreateRequest.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. DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).build();
  61. DeleteResponse deleteResponse = client.indices().delete(deleteRequest);
  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