Java client

    For example, you can submit requests to your cluster using objects to create indices, add data to documents, or complete some other operation using the client’s built-in methods.

    To start using the OpenSearch Java client, ensure that you have the following dependencies in your project’s file:

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

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

    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>

    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).

    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.

    Initialize 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 to use 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. public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
    33. return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    34. }
    35. }).build();
    36. Transport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    37. OpenSearchClient client = new OpenSearchClient(transport);
    38. }
    39. }

    Create an index with non-default settings

    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);

    Search for the document

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

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

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

    Delete the index

    Complete code sample

    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. //Initialize the client with SSL and TLS enabled
    29. restClient = RestClient.builder(new HttpHost("localhost", 9200, "https")).
    30. setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    31. public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
    32. return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    33. }
    34. }).build();
    35. Transport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    36. OpenSearchClient client = new OpenSearchClient(transport);
    37. //Create the index
    38. String index = "sample-index";
    39. CreateRequest createIndexRequest = new CreateRequest.Builder().index(index).build();
    40. client.indices().create(createIndexRequest);
    41. //Add some settings to the index
    42. IndexSettings indexSettings = new IndexSettings.Builder().autoExpandReplicas("0-all").build();
    43. IndexSettingsBody settingsBody = new IndexSettingsBody.Builder().settings(indexSettings).build();
    44. PutSettingsRequest putSettingsRequest = new PutSettingsRequest.Builder().index(index).value(settingsBody).build();
    45. client.indices().putSettings(putSettingsRequest);
    46. //Index some data
    47. IndexData indexData = new IndexData("first_name", "Bruce");
    48. IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").value(indexData).build();
    49. client.index(indexRequest);
    50. //Search for the document
    51. SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
    52. for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
    53. System.out.println(searchResponse.hits().hits().get(i).source());
    54. }
    55. //Delete the document
    56. client.delete(b -> b.index(index).id("1"));
    57. // Delete the index
    58. DeleteRequest deleteRequest = new DeleteRequest.Builder().index(index).build();
    59. DeleteResponse deleteResponse = client.indices().delete(deleteRequest);
    60. } catch (IOException e){
    61. System.out.println(e.toString());
    62. } finally {
    63. try {
    64. if (restClient != null) {
    65. restClient.close();
    66. }
    67. } catch (IOException e) {
    68. System.out.println(e.toString());
    69. }
    70. }
    71. }