×
Community Blog Unlocking the Power of Elasticsearch with Java High Level REST Client (6.7.x)

Unlocking the Power of Elasticsearch with Java High Level REST Client (6.7.x)

This step-by-step guide includes setup instructions, code snippets, and detailed configurations to get you started.

Introduction

Are you ready to take your Elasticsearch skills to the next level? Java High Level REST Client (6.7.x) offers an efficient and powerful way to interact with your Elasticsearch clusters. This guide will walk you through the process of setting up and using the High Level REST Client to call Elasticsearch Java APIs on an Alibaba Cloud Elasticsearch cluster.

Preparations

Step 1: Install a JDK

Ensure you have JDK 1.8 or later installed on your system. For installation details, refer to Install a JDK.

Step 2: Create an Alibaba Cloud Elasticsearch Cluster

Create a cluster with a version that matches or is newer than the version of your Java High Level REST Client. For detailed guidance, see Create an Alibaba Cloud Elasticsearch cluster.

Step 3: Enable Auto Indexing

Enable the Auto Indexing feature in the Elasticsearch cluster YAML configuration file to prevent potential issues. For instructions, see Configure the YML file.

Step 4: Configure IP Address Whitelist

To ensure proper communication, configure the IP address whitelist appropriately. For more details, see Configure a public or private IP address whitelist.

Step 5: Create a Java Maven Project

Add the necessary dependencies to your pom.xml file. Ensure you use the correct version numbers.

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.7.0</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>

Example: Managing an Index

The following example demonstrates how to create and delete an index using Java High Level REST Client. Customize the {} placeholders with your actual 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 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) {
        // Use basic access authentication for the Elasticsearch cluster.
        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}", "{type_name}", "{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}", "{type_name}", "{doc_id}");
            DeleteResponse deleteResponse = highClient.delete(deleteRequest, COMMON_OPTIONS);
            System.out.println("Delete document successfully! \n" + deleteResponse.toString() + "\n" + deleteResponse.status());

            highClient.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

High-Concurrency Configuration

For high-concurrency environments, increase the number of client connections as shown below:

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

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

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

Conclusion

Utilizing Java High Level REST Client (6.7.x) offers a robust and flexible way to manage your Alibaba Cloud Elasticsearch cluster effectively. Follow this guide to maximize your Elasticsearch capabilities seamlessly.
Click here to embark on Your 30-Day Free Trial

0 1 0
Share on

Data Geek

100 posts | 4 followers

You may also like

Comments

Data Geek

100 posts | 4 followers

Related Products