Elevate Your Elasticsearch Experience with Java High Level REST Client (7.x)
Tags: javascript, tutorial, productivity, webdev
Published: 2024-07-17 01:45:55

## 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](https://www.alibabacloud.com/en/product/elasticsearch) cluster.
<a name="IRk1L"></a>

## Preparations

<a name="TcFhZ"></a>

### 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](https://www.alibabacloud.com/en/product/elasticsearch).
<a name="QgbUJ"></a>

### Step 2: Enable Auto Indexing

Enable the Auto Indexing feature in the YAML configuration file. For details, see [Configure the YML file](https://www.alibabacloud.com/help/en/elasticsearch/latest/configuration).
<a name="HHMzG"></a>

### 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](https://www.alibabacloud.com/help/en/elasticsearch/latest/configure-a-whitelist).
<a name="UDL4R"></a>

### Step 4: Install JDK

Install Java Development Kit (JDK) version 1.8 or later. For more information, see [Install a JDK](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html).
<a name="FB5dQ"></a>

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

```xml
<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>
```

<a name="r4Cpi"></a>

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

```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 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();
        }
    }
}
```

<a name="j7HBS"></a>

## High-Concurrency Configuration

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

```java
httpClientBuilder.setMaxConnTotal(500);
httpClientBuilder.setMaxConnPerRoute(300);
```

Sample code snippet:

```java
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);
    }
  })
);
```

For more details on features and configurations, see the official [Java High Level REST Client documentation](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html).
<a name="M4R9H"></a>

## Conclusion

Using the Java High Level REST Client ensures efficient interaction with your [Alibaba Cloud Elasticsearch](https://www.alibabacloud.com/en/product/elasticsearch) cluster. Follow this guide to make the most out of your Elasticsearch setup.<br />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. <br />
[Click here to embark on Your 30-Day Free Trial](https://c.tb.cn/F3.bTfFpS)