All Products
Search
Document Center

Lindorm:Java Low Level REST Client

Last Updated:Jun 26, 2024

The Java Low Level REST Client is the basic REST client provided by Elasticsearch. Its API operations do not encode or decode data. LindormSearch is compatible with Elasticsearch 7.10 and earlier versions. To customize the requests and responses when you connect to LindormSearch, you can use the Java Low Level REST Client.

Prerequisites

  • Java Development Kit (JDK) V1.8 or later is installed.

  • LindormSearch is activated for your Lindorm instance. For more information, see Activate LindormSearch.

  • The IP address of your client is added to the whitelist of the Lindorm instance. For more information, see Configure whitelists.

Procedure

  1. Install the Java Low Level Rest Client. For example, you can add the following dependencies to the pom.xml file in your Maven project. The following example shows how to add dependencies to the configuration file in a Maven project:

    <dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>elasticsearch-rest-client</artifactId>
      <version>7.10.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.8.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.7</version>
    </dependency>
  2. Configure connection parameters.

    // Specify the LindormSearch endpoint for Elasticsearch.
    String search_url = "ld-t4n5668xk31ui****-proxy-search-public.lindorm.rds.aliyuncs.com";
    int search_port = 30070;
    
    // Specify the username and password used to connect to LindormSearch.
    String username = "user";
    String password = "test";
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(search_url, search_port));
    restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
      @Override
      public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      }
    });

    Parameters

    Parameter

    Description

    search_url

    The LindormSearch endpoint for Elasticsearch. For more information about how to obtain the endpoint, see View endpoints.

    Important
    • If your application is deployed on an ECS instance, we recommend that you use a VPC to connect to the Lindorm instance to ensure higher security and lower network latency.

    • If your application is deployed on a local server and needs to connect to the Lindorm instance over the Internet, you can perform the following steps to enable the public endpoint of the instance in the Lindorm console: In the left-side navigation pane, click Database Connections. On the page that appears, click the Search Engine tab. Then, click Enable Public Endpoint in the upper-right corner.

    • If you use a VPC to access the Lindorm instance, specify the LindormSearch VPC endpoint for Elasticsearch in the value of search_url. If you use the Internet to access the Lindorm instance, specify the LindormSearch Internet endpoint for Elasticsearch in the value of search_url.

    search_port

    The port used to access the LindormSearch endpoint for Elasticsearch. The value of this parameter is fixed to 30070.

    username

    The username and password used to access LindormSearch.

    You can perform the following steps to obtain the default username and password: In the left-side navigation pane, click Database Connections. On the page that appears, click the Search Engine tab. Then, view the username and password displayed on this tab.

    password

  3. Use the Java Low Level REST Client to connect to and use LindormSearch.

    The following operations are performed by the sample code:

    • Create a search index: A search index named lindorm_index is created.

    • Write data: 5,000 documents are written to LindormSearch in a batch.

    • Query data: Initiate a refresh request to display the data written to LindormSearch. In the sample code, two requests are sent to individually query all documents in the index and the document with the specified ID in the index.

    • Delete data: Delete the document whose ID is test and delete the lindorm_index index.

    try (RestClient restClient = restClientBuilder.build()) {
      String indexName = "lindorm_index";
    
      // Create a search index.
      Request indexRequest = new Request("PUT", "/" + indexName);
      indexRequest.setJsonEntity("{" +
        "  \"settings\":{" +
        "    \"index.number_of_shards\": 1" +
        "  }," +
        "  \"mappings\":{" +
        "    \"properties\":{" +
        "      \"name\":{" +
        "        \"type\":\"text\"" +
        "      }" +
        "    }" +
        "  }" +
        "}");
      Response response = restClient.performRequest(indexRequest);
      String responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);
    
      // Write multiple documents to LindormSearch in a batch.
      Random random = new Random();
      Request bulkRequest = new Request("POST", "/_bulk");
      StringBuilder bulkJsonBuilder = new StringBuilder();
      for (int i = 0; i < 5000; i++) {
        // Replace the fields and values in the code with actual ones in your business.
        bulkJsonBuilder.append("{\"index\":{\"_index\":\"").append(indexName).append("\",\"_id\":\"").append(i).append("\"}}").append("\n");
        String value = random.nextInt() + "";
        bulkJsonBuilder.append("{\"field1\":\"").append(value).append("\",\"field2\":\"").append(value).append("\"}").append("\n");
      }
      bulkRequest.setJsonEntity(bulkJsonBuilder.toString());
      response = restClient.performRequest(bulkRequest);
    
      // Initiate a refresh request to display the data written to LindormSearch.
      response = restClient.performRequest(new Request("POST", "/" + indexName + "/_refresh"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);
    
      // Query all data in the index. By default, up to 10 results are returned.
      response = restClient.performRequest(new Request("GET", "/" + indexName + "/_search"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);
    
      // Query documents whose ID is 0 in the index.
      response = restClient.performRequest(new Request("GET", "/" + indexName + "/_doc/0"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);
    
      // Delete the index.
      response = restClient.performRequest(new Request("DELETE", "/" + indexName));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);
    
    } catch (Exception e) {
      System.out.println("msg: " + e.getMessage());
    }

Sample code

The following code provides a complete example on how to use Java Low Level REST Client to connect to LindormSearch and perform operations in LindormSearch:

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.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;

import java.util.Random;

public class RestLClientTest {
  public static void main(String[] args) {
    // Specify the LindormSearch endpoint for Elasticsearch.
    String search_url = "ld-t4n5668xk31ui****-proxy-search-public.lindorm.rds.aliyuncs.com";
    int search_port = 30070;

    // Specify the username and password used to connect to LindormSearch.
    String username = "user";
    String password = "test";

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(search_url, search_port));
    restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
      @Override
      public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      }
    });

    try (RestClient restClient = restClientBuilder.build()) {
      String indexName = "lindorm_index";

      // Create a search index.
      Request indexRequest = new Request("PUT", "/" + indexName);
      indexRequest.setJsonEntity("{" +
        "  \"settings\":{" +
        "    \"index.number_of_shards\": 1" +
        "  }," +
        "  \"mappings\":{" +
        "    \"properties\":{" +
        "      \"name\":{" +
        "        \"type\":\"text\"" +
        "      }" +
        "    }" +
        "  }" +
        "}");
      Response response = restClient.performRequest(indexRequest);
      String responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);

      // Write multiple documents to LindormSearch in a batch.
      Random random = new Random();
      Request bulkRequest = new Request("POST", "/_bulk");
      StringBuilder bulkJsonBuilder = new StringBuilder();
      for (int i = 0; i < 5000; i++) {
        // Replace the fields and values in the code with actual ones in your business.
        bulkJsonBuilder.append("{\"index\":{\"_index\":\"").append(indexName).append("\",\"_id\":\"").append(i).append("\"}}").append("\n");
        String value = random.nextInt() + "";
        bulkJsonBuilder.append("{\"field1\":\"").append(value).append("\",\"field2\":\"").append(value).append("\"}").append("\n");
      }
      bulkRequest.setJsonEntity(bulkJsonBuilder.toString());
      response = restClient.performRequest(bulkRequest);

      // Initiate a refresh request to display the data written to LindormSearch.
      response = restClient.performRequest(new Request("POST", "/" + indexName + "/_refresh"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);

      // Query all data in the index. By default, up to 10 results are returned.
      response = restClient.performRequest(new Request("GET", "/" + indexName + "/_search"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);

      // Query documents whose ID is 0 in the index.
      response = restClient.performRequest(new Request("GET", "/" + indexName + "/_doc/0"));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);

      // Delete the index.
      response = restClient.performRequest(new Request("DELETE", "/" + indexName));
      responseBody = EntityUtils.toString(response.getEntity());
      System.out.println("responseBody = " + responseBody);

    } catch (Exception e) {
      System.out.println("msg: " + e.getMessage());
    }
  }
}

The following result is returned:

responseBody = {"acknowledged":true,"shards_acknowledged":true,"index":"lindorm_index"}
responseBody = {"_shards":{"total":1,"successful":1,"failed":0}}
responseBody = {"took":6,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":5000,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"lindorm_index","_id":"0","_score":1.0,"_source":{"field1":"2127821774","field2":"2127821774"}},{"_index":"lindorm_index","_id":"1","_score":1.0,"_source":{"field1":"1820331840","field2":"1820331840"}},{"_index":"lindorm_index","_id":"2","_score":1.0,"_source":{"field1":"-388903172","field2":"-388903172"}},{"_index":"lindorm_index","_id":"3","_score":1.0,"_source":{"field1":"-68048869","field2":"-68048869"}},{"_index":"lindorm_index","_id":"4","_score":1.0,"_source":{"field1":"1865955199","field2":"1865955199"}},{"_index":"lindorm_index","_id":"5","_score":1.0,"_source":{"field1":"1088273523","field2":"1088273523"}},{"_index":"lindorm_index","_id":"6","_score":1.0,"_source":{"field1":"-1529281106","field2":"-1529281106"}},{"_index":"lindorm_index","_id":"7","_score":1.0,"_source":{"field1":"-1185412160","field2":"-1185412160"}},{"_index":"lindorm_index","_id":"8","_score":1.0,"_source":{"field1":"-1243760053","field2":"-1243760053"}},{"_index":"lindorm_index","_id":"9","_score":1.0,"_source":{"field1":"1066058716","field2":"1066058716"}}]}}
responseBody = {"_index":"lindorm_index","_id":"0","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"field1":"2127821774","field2":"2127821774"}}
responseBody = {"acknowledged":true}