RestClient operates on the ES index library

ES officially provides clients in various languages to operate ES. The essence of these clients is to assemble DSL statements and send them to ES through http requests. Official Document Address: https://www.elastic.co/guide/en/elasticsearch/client/index.html

There are two more types of Java Rest Client s:

  • Java Low Level Rest Client

  • Java High Level Rest Client

We learned the Java HighLevel Rest Client client API

Example hotel database table structure:

CREATE TABLE `tb_hotel` (
  `id` bigint(20) NOT NULL COMMENT 'Hotel id',
  `name` varchar(255) NOT NULL COMMENT 'Hotel name; Example: 7-day Hotel',
  `address` varchar(255) NOT NULL COMMENT 'Hotel's address; Example: Headway',
  `price` int(10) NOT NULL COMMENT 'Hotel price; Example: 329',
  `score` int(2) NOT NULL COMMENT 'Hotel rating; Example: 45, or 4.5 branch',
  `brand` varchar(32) NOT NULL COMMENT 'Hotel brand; Example: Home',
  `city` varchar(32) NOT NULL COMMENT 'City where you live; Example: Shanghai',
  `star_name` varchar(16) DEFAULT NULL COMMENT 'Hotel stars, from low to high: 1 star to 5 stars, 1 drill to 5 drills',
  `business` varchar(255) DEFAULT NULL COMMENT 'Business Circle; Example: Hongqiao',
  `latitude` varchar(32) NOT NULL COMMENT 'Latitude; Example: 31.2497',
  `longitude` varchar(32) NOT NULL COMMENT 'Longitude; Example: 120.3925',
  `pic` varchar(255) DEFAULT NULL COMMENT 'Pictures of hotels; example:/img/1.jpg',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

  

1.mapping mapping analysis

The key to creating an index library is the mapping map, which considers information such as:

  • Field name

  • Field data type

  • Participate in search

  • Is participle required

  • If a word breaker, what is the word breaker?

Where:

  • Field name, field data type, refer to the name and type of data table structure

  • Participation in search To analyze business decisions, such as picture addresses, you don't need to participate in search

  • Whether or not to split words depends on the content. If the content is a whole, there is no need to split words, and vice versa, there is a need to split words.

  • Word Separator, we can use ik_uniformly Max_ Word

 

Take a look at the index library structure for hotel data:

PUT /hotel
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "ik_max_word",
        "copy_to": "all"
      },
      "address":{
        "type": "keyword",
        "index": false
      },
      "price":{
        "type": "integer"
      },
      "score":{
        "type": "integer"
      },
      "brand":{
        "type": "keyword",
        "copy_to": "all"
      },
      "city":{
        "type": "keyword",
        "copy_to": "all"
      },
      "starName":{
        "type": "keyword"
      },
      "business":{
        "type": "keyword"
      },
      "location":{
        "type": "geo_point"
      },
      "pic":{
        "type": "keyword",
        "index": false
      },
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

  

Several special field descriptions:

  • location: Geographic coordinates containing precision, latitude

  • all: A combined field whose purpose is to use copy_for values from multiple fields To merge and provide users with search

 

Geographic coordinate description:

 

 

 

2. Initialize RestClient

In the API provided by elasticsearch, all interaction with elasticsearch is encapsulated in a class named RestHighLevelClient, which must first be initialized and connected to elasticsearch.

There are three steps:

1) ReestHighLevelClient dependency with es introduced:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

2) Because the default ES version of SpringBoot is 7.6.2, we need to override the default ES version, which must be the same as the installed ES version number:

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.12.1</elasticsearch.version>
</properties>

3) Initialize RestHighLevelClient:

The code to initialize is as follows:

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
));

  

For the convenience of unit testing, we create a test class, HotelIndexTest, and write the initialization code in the @BeforeEach method:

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class HotelIndexTest {
    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

3. Create Index Library

The API s for creating index libraries are as follows:

 

 

 

The code is divided into three steps:

  • 1) Create the Request object. Request is CreateIndexRequest because it is an operation to create an index library.

  • 2) Adding request parameters is actually the JSON parameter part of the DSL. Because the JSON string is very long, here is the static string constant MAPPING_defined TEMPLATE, to make the code look more elegant.

  • 3) Send the request, and the return value of the client.indices() method is of type IndicesClient, encapsulating all the methods related to the operation of the index library.

 

Complete example

Create a class that defines the JSON string constant for the mapping map:

public class HotelConstants {
    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"starName\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

  

Write unit tests to create indexes:

@Test
void createHotelIndex() throws IOException {
    // 1. Create Request Object
    CreateIndexRequest request = new CreateIndexRequest("hotel");
    // 2. Prepare the parameters for the request: DSL statement
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    // 3. Send Request
    client.indices().create(request, RequestOptions.DEFAULT);
}

4. Delete Index Library

Deleting a DSL statement from an index library is very simple:

DELETE /hotel

  

Compared to creating an index library:

  • Request mode changed from PUT to DELTE

  • Request path unchanged

  • No Request Parameters

So notice that the code differences are reflected in the Request object. Still three steps:

  • 1) Create the Request object. This time the DeleteIndexRequest object

  • 2) Prepare parameters. No reference here

  • 3) Send the request. Use delete method instead

Write unit tests to remove indexes:

@Test
void testDeleteHotelIndex() throws IOException {
    // 1. Create Request Object
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    // 2. Send Request
    client.indices().delete(request, RequestOptions.DEFAULT);
}

  

5. Determine if an index library exists

To determine whether an index library exists is essentially a query and the corresponding DSL is:

GET /hotel

  

Therefore, it is similar to the Java code flow that was deleted. Still three steps:

  • 1) Create the Request object. This time the GetIndexRequest object

  • 2) Prepare parameters. No reference here

  • 3) Send the request. Use exists method instead

@Test
void testExistsHotelIndex() throws IOException {
    // 1. Create Request Object
    GetIndexRequest request = new GetIndexRequest("hotel");
    // 2. Send Request
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    // 3. Output
    System.err.println(exists ? "Index library already exists!" : "Index library does not exist!");
}

  

summary

The JavaRestClient process for manipulating elasticsearch is basically similar. The core is the client.indices() method to get the operation object of the index library.

Basic steps for index library operation:

  • Initialize RestHighLevelClient

  • Create an XxxIndexRequest. XXX is Create, Get, Delete

  • Preparing DSL (Create required, others no parameters)

  • Send the request. Call the RestHighLevelClient#indices().xxx() method, XXX is create, exists, delete

 

Tags: ElasticSearch

Posted on Sun, 07 Nov 2021 12:06:24 -0500 by comcentury