This topic describes how to use the Elasticsearch Java APIs. Java High Level REST Client 6.3.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 Elasticsearch cluster. Ensure that the cluster version is higher than or equal to that of Java High Level REST Client.

    In this topic, create an Elasticsearch cluster whose version is V6.3.2. For more information, see Create an Elasticsearch cluster.

    Notice Java High Level REST Client is forward compatible. For example, High Level REST Client 6.3.2 can communicate with an Elasticsearch cluster V6.3.2 or later. To ensure that you can use the features of the latest client, we recommend that you use 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, 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.3.2</version>
</dependency>

Examples

The following sample code uses the index API to index the document and then uses the delete API to delete the index:

// The file path is src/main/java/RestClientTest.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.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

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

public class RestClientTest {
    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 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 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 their values.
            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:
            IndexResponse indexResponse = highClient.index(indexRequest);

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

            System.out.println("Delete document successfully!") ;

            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.