This topic describes how to use the Elasticsearch Java APIs. Java High Level REST Client 6.7.x is used as an example.

Preparations

  • Install a JDK. The JDK version must be 1.8 or later.

    For more information, see Install the JDK.

  • Create an Alibaba Cloud Elasticsearch cluster whose version is V6.7.0. Make sure that this version is higher than or equal to that of the Java High Level REST Client.

    For more information, see Create an Elasticsearch cluster.

    Notice Java High Level REST Client is forward compatible. For example, Java High Level REST Client 6.7.0 can communicate with Elasticsearch clusters V6.7.0 or later. To ensure that you can use the features of the latest client, we recommend that you use a Java High Level REST Client that matches your cluster.
  • Enable the Auto Indexing feature for the Elasticsearch cluster.

    For more information, see Enable auto indexing.

    If the Auto Indexing feature is not enabled, the following error is reported.Error
  • Enable the public endpoint of your Elasticsearch cluster and add the public IP address of your host to the public whitelist of the cluster.

    For more information, see Configure a whitelist to access an Elasticsearch cluster over the Internet or a VPC.

    Note If you want to query the public IP address of your host, If you want to query the public IP address of your host, open Google Chrome, enter IP, and click What Is My IP Address. You can obtain the public IP address of your host on the web page that appears.
  • Create a Java Maven project and add the Project Object Model (POM) dependencies to the pom.xml file of the Java project. For more information, see POM dependencies. Add POM dependencies

POM dependencies

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.7.0</version>
</dependency>

RequestOptions

Java REST Client 6.7.0 introduces RequestOptions based on version 6.3.2. You can specify more options for requests without affecting the execution of the requests.

The following sample code is executed in a client environment that has limited JVM memory. You can limit the value of ResponseConsumer to adjust the size of the cache for asynchronous responses. For more information about the complete sample code, see Examples.

private static final RequestOptions COMMON_OPTIONS;

static {
    RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

    // The default cache size is 100 MiB. Change it to 30 MiB.
    builder.setHttpAsyncResponseConsumerFactory(
            new HttpAsyncResponseConsumerFactory
                    .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
    COMMON_OPTIONS = builder.build();
}
// Run the following command in parallel and use the custom configuration of RequestOptions:
IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);

For more information about how to use the RequestOptions class, see RequestOptions.

Examples

The following code is the complete sample code of RequestOptions. The following sample code calls the index API to create an index and calls the delete API to delete the index. The code is executed in a client environment that has limited JVM memory. You can limit the value of ResponseConsumer to adjust the size of the cache for asynchronous responses.

// The file path is src/main/java/RestClientTest67.java.
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RestClientTest67 {

    private static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

        // The default cache size is 100 MiB. Change it to 30 MiB.
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    public static void main(String[] args) {
        // The Elasticsearch cluster requires basic authentication.
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
       // Use the username and password that you have specified when you create the Alibaba Cloud Elasticsearch cluster. You can also use username and password to log on to the Kibana console.
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("{username}", "{password}"));

        // Create a Java REST client by using the builder and configure HttpClientConfigCallback for the HTTP client.
       // Specify the public endpoint of the Elasticsearch cluster. To obtain the endpoint, you can perform the following operations: Log on to the Alibaba Cloud Elasticsearch console. In the left-side navigation pane, click Elasticsearch Clusters. On the Clusters page, click the ID of the Elasticsearch cluster in the Cluster ID/Name column. On the Basic Information page, obtain the public endpoint of the Elasticsearch cluster.
        RestClientBuilder builder = RestClient.builder(new HttpHost("{Elasticsearch cluster endpoint}", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // Create a RestHighLevelClient instance by using the REST low-level client builder.
        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        try {
            // Create a request.
            Map<String, Object> jsonMap = new HashMap<>();
           // field_01 and field_02 are the field names, and value_01 and value_02 are the values of field_01 and field_02.
           jsonMap.put("{field_01}", "{value_01}");
           jsonMap.put("{field_02}", "{value_02}");
           // index_name is the index name, type_name is the type name, and doc_id is the document ID.
           IndexRequest indexRequest = new IndexRequest("{index_name}", "{type_name}", "{doc_id}").source(jsonMap);

            // Run the following command in parallel and use the custom configuration of RequestOptions:
            IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);

            long version = indexResponse.getVersion();

            System.out.println("Index document successfully! " + version);
            // index_name is the index name, type_name is the type name, and doc_id is the document ID. The index name, type name, and document ID are the same as those you have specified when you create the index.
            DeleteRequest request = new DeleteRequest("{index_name}", "{type_name}", "{doc_id}");
            DeleteResponse deleteResponse = highClient.delete(request, COMMON_OPTIONS);

            System.out.println("Delete document successfully! \n" + deleteResponse.toString() + "\n" + deleteResponse.status());

            highClient.close();

        } catch (IOException ioException) {
            // Handle exceptions.
        }
    }
}

You can replace the parameters in the preceding sample code that are contained within braces {} with service-specific parameters. For more information, see the code comments.

For more information about the features of Java High Level REST Client, see Java High Level REST Client.