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
A Java environment with JDK 1.8 or a later version must be installed.
LindormSearch is activated for your Lindorm instance. For more information, see Activation guide.
The IP address of your client is added to the whitelist of the Lindorm instance. For more information, see Configure a whitelist.
Procedure
Install the Java Low Level REST Client. For a Maven project, add the following dependencies to the
dependenciessection of thepom.xmlfile:<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>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.
ImportantIf 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 locally and connects to the Lindorm instance over the public network, you must first enable the public endpoint in the console. In the navigation pane on the left, click Database Connections. Click the Search Engine tab, and then click Enable Public Endpoint in the upper-right corner.
To connect over a VPC, set search_url to the VPC endpoint. To connect over the public network, set search_url to the Internet endpoint.
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 to access the search engine.
To get the default username and password, go to the console. In the navigation pane on the left, click Database Connections. You can find the credentials on the Search Engine tab.
password
You can access the search engine with the Java Low Level REST Client object.
The sample code includes the following parts:
Create a search index: A search index named lindorm_index is created.
Data writing: Write 5,000 documents 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()); }
Complete example
The complete sample code is as follows:
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}