"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Elevate Your Elasticsearch Experience with Java High Level REST Client ()

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

Published on 2024-08-01
Browse:490

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

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.


    org.elasticsearch.client
    elasticsearch-rest-high-level-client
    7.x


    org.apache.logging.log4j
    log4j-core
    2.20.0


    org.apache.logging.log4j
    log4j-api
    2.20.0

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

High-Concurrency Configuration

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

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

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

Release Statement This article is reproduced at: https://dev.to/a_lucas/elevate-your-elasticsearch-experience-with-java-high-level-rest-client-7x-348k?1 If there is any infringement, please contact [email protected] delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3