×
Community Blog Mastering Elasticsearch with Java High Level REST Client (6.3.x)

Mastering Elasticsearch with Java High Level REST Client (6.3.x)

This article guides you through using Java High Level REST Client 6.3.x to efficiently interact with your Alibaba Cloud Elasticsearch cluster.

Introduction

Harness the power of Elasticsearch by using the Java High Level REST Client 6.3.x. This powerful client library allows you to perform a multitude of operations on your Alibaba Cloud Elasticsearch cluster with ease. In this guide, we’ll walk you through the setup and use of the Java High Level REST Client to call Elasticsearch Java APIs.

Preparations

Step 1: Install JDK

Ensure you have JDK 1.8 or later installed. 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

Ensure proper communication by configuring 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</groupId>

    <artifactId>elasticsearch</artifactId>

    <version>6.3.2</version>

</dependency>

<dependency>
    <groupId>org.elasticsearch.client</groupId>

    <artifactId>elasticsearch-rest-high-level-client</artifactId>

    <version>6.3.2</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.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 RestClientTest63 {
    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}"));

        // Create a Java REST client by using the builder and configure HttpClientConfigCallback for the HTTP client.
        // Specify the public endpoint of the Elasticsearch cluster. You can obtain the endpoint from the Basic Information page of the cluster.
        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);
                    }
                });

        // Use the REST low-level client builder to create a RestHighLevelClient instance.
        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        try {
            // Create a request.
            Map<String, Object> jsonMap = new HashMap<>();
            // field_01 and field_02 are 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 code in parallel.
            IndexResponse indexResponse = highClient.index(indexRequest);
            long version = indexResponse.getVersion();
            System.out.println("Index document successfully! " + version);

            // Delete the index.
            DeleteRequest deleteRequest = new DeleteRequest("{index_name}", "{type_name}", "{doc_id}");
            DeleteResponse deleteResponse = highClient.delete(deleteRequest);
            System.out.println("Delete document successfully!");

            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.3.x) offers a robust and flexible way to manage your Alibaba Cloud Elasticsearch cluster effectively. Follow this guide to maximize your Elasticsearch capabilities seamlessly.
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

0 1 0
Share on

Data Geek

100 posts | 4 followers

You may also like

Comments

Data Geek

100 posts | 4 followers

Related Products