×
Community Blog Mastering Elasticsearch with Java Low Level REST Client (5.x)

Mastering Elasticsearch with Java Low Level REST Client (5.x)

With detailed steps and code examples, this guide simplifies the process from setup to execution of basic operations.

Introduction

Unlock the potential of Elasticsearch by leveraging the Java Low Level REST Client 5.x. This powerful library enables seamless interaction with your Alibaba Cloud Elasticsearch cluster. This guide provides a comprehensive overview of setting up and utilizing the Java Low Level REST Client to call Elasticsearch Java APIs.

Precautions

  • Compatibility: Low Level REST Client 5.x is compatible only with Alibaba Cloud Elasticsearch V5.5.3. Ensure the client version matches your cluster version.
  • Security: Avoid using 0.0.0.0/0 for IP address whitelisting unless necessary, due to security risks.

Preparations

Step 1: Install a 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 version V5.5.3 for compatibility. For a step-by-step guide, 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.client</groupId>

    <artifactId>rest</artifactId>

    <version>5.5.3</version>

</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>

    <artifactId>log4j-core</artifactId>

    <version>2.7.1</version>

</dependency>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>

    <artifactId>log4j-api</artifactId>

    <version>2.7.1</version>

</dependency>

Example: Managing an Index

The following example demonstrates how to create and retrieve an index using Java Low Level REST Client. Customize the {} placeholders with your actual parameters.

import org.apache.http.HttpEntity;
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.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import java.io.IOException;
import java.util.Collections;

public class RestClientTest55 {
    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.
        RestClient restClient = RestClient.builder(new HttpHost("HOST", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }).build();
        try {
            // field_01 and field_02 are field names, and value_01 and value_02 are the values of field_01 and field_02.
            HttpEntity entity = new NStringEntity("{\n\"field_01\" : \"value_01\"\n,\n\"field_02\" : \"value_02\"\n}", ContentType.APPLICATION_JSON);
            // index_name is the index name, type_name is the type name, and doc_id is the document ID.
            Response indexResponse = restClient.performRequest(
                    "PUT",
                    "/index_name/type_name/doc_id",
                    Collections.<String, String>emptyMap(),
                    entity);

            // Retrieve the document.
            Response response = restClient.performRequest("GET", "/index_name/type_name/doc_id",
                    Collections.singletonMap("pretty", "true"));
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Parameter Descriptions

  • USERNAME: Replace with the username of your Elasticsearch cluster.
  • PASSWORD: Replace with the password of your Elasticsearch cluster.
  • HOST: Replace with the public or internal endpoint of your Elasticsearch cluster, obtainable from the Basic Information page.

Conclusion

Using the Java Low Level REST Client (5.x) provides a robust and efficient way to manage your Alibaba Cloud Elasticsearch cluster. This guide offers essential steps and sample code to help you get started quickly and effectively.
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

98 posts | 4 followers

You may also like

Comments

Data Geek

98 posts | 4 followers

Related Products