DEV Community

Cover image for Elevate Your Elasticsearch Experience with Java High Level REST Client (7.x)
A_Lucas
A_Lucas

Posted on

Elevate Your Elasticsearch Experience with Java High Level REST Client (7.x)

Introduction

Java High Level REST Client (7.x) is a powerful tool for interacting with Elasticsearch clusters, making server communication more accessible and efficient. In this guide, we will walk you through the steps to use the High Level REST Client to call Elasticsearch Java APIs on an Alibaba Cloud Elasticsearch cluster.

Preparations

Step 1: Create an Elasticsearch Cluster

Ensure your cluster version is the same as or newer than the Java High Level REST Client version you plan to use. For step-by-step instructions, see Create an Alibaba Cloud Elasticsearch cluster.

Step 2: Enable Auto Indexing

Enable the Auto Indexing feature in the YAML configuration file. For details, see Configure the YML file.

Step 3: Configure IP Address Whitelist

Ensure proper communication by configuring an IP address whitelist. If you're accessing the cluster over the Internet, allow requests from the required IP addresses by following the guidelines in Configure a public or private IP address whitelist.

Step 4: Install JDK

Install Java Development Kit (JDK) version 1.8 or later. For more information, see Install a JDK.

Step 5: Create a Java Maven Project

Add the necessary dependencies to your pom.xml file. Change the version number in the dependencies from 7.x to the specific version of the High Level REST Client you are using.

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.x</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.20.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.20.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Example: Managing an Index

Below is an example of creating and deleting an index using the High Level REST Client. Replace placeholders {} with your specific parameters.

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 RestClientExample {
    private static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    public static void main(String[] args) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, 
            new UsernamePasswordCredentials("{Username}", "{Password}"));

        RestClientBuilder builder = RestClient.builder(new HttpHost("{Endpoint of the Elasticsearch cluster}", 9200, "http"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        try {
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("{field_01}", "{value_01}");
            jsonMap.put("{field_02}", "{value_02}");

            IndexRequest indexRequest = new IndexRequest("{index_name}", "_doc", "{doc_id}").source(jsonMap);
            IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);
            long version = indexResponse.getVersion();
            System.out.println("Index document successfully! " + version);

            DeleteRequest deleteRequest = new DeleteRequest("{index_name}", "_doc", "{doc_id}");
            DeleteResponse deleteResponse = highClient.delete(deleteRequest, COMMON_OPTIONS);
            System.out.println("Delete document successfully! \n" + deleteResponse.toString());

            highClient.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

High-Concurrency Configuration

For high-concurrency scenarios, increase the number of client connections:

httpClientBuilder.setMaxConnTotal(500);
httpClientBuilder.setMaxConnPerRoute(300);
Enter fullscreen mode Exit fullscreen mode

Sample code snippet:

String host = "127.0.0.1";
int port = 9200;
String username = "elastic";
String password = "passwd";
final int max_conn_total = 500;
final int max_conn_per_route = 300;

RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
  RestClient.builder(new HttpHost(host, port, "http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
      httpClientBuilder.setMaxConnTotal(max_conn_total);
      httpClientBuilder.setMaxConnPerRoute(max_conn_per_route);
      return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
  })
);
Enter fullscreen mode Exit fullscreen mode

For more details on features and configurations, see the official Java High Level REST Client documentation.

Conclusion

Using the Java High Level REST Client ensures efficient interaction with your Alibaba Cloud Elasticsearch cluster. Follow this guide to make the most out of your Elasticsearch setup.
Ready to start your journey with Elasticsearch on Alibaba Cloud? Explore our tailored Cloud solutions and services to transform your data into a visual masterpiece.

Click here to embark on Your 30-Day Free Trial

Top comments (0)