SpringBoot 整合 Elasticsearch8(最新API——Java API Client for Elasticsearch)—— 1、索引操作

3,384 阅读2分钟

SpringBoot 整合 Elasticsearch8.0(最新API——Java API Client for Elasticsearch)—— 1、索引操作

在这里插入图片描述

从官方文档中可以发现我们最多使用的 Java High Level RESRT Client API 在 7.15.0 后被标记过时

应此使用官网推荐使用的 Java API Client for Elasticsearch Api

在这里插入图片描述

官方文档地址:Elasticsearch Java API Client 8.1| Elastic

导入依赖

<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.1.1</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

<!-- Needed only if you use the spring-boot Maven plugin -->
<dependency> 
    <groupId>jakarta.json</groupId>
    <artifactId>jakarta.json-api</artifactId>
    <version>2.0.1</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

注意: 使用的Elasticsearch的版本必须与 elasticsearch-java jar 包的版本保持一致

1、创建连接客户端

@Test
void ElasticsearchClientBuild() {
    // Create the low-level client
    RestClient restClient = RestClient.builder(
        new HttpHost("127.0.0.1", 9200)).build();

    // Create the transport with a Jackson mapper
    ElasticsearchTransport transport = new RestClientTransport(
        restClient, new JacksonJsonpMapper());

    // And create the API client
    ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);
    System.out.println("elasticsearchClient = " + elasticsearchClient);
}

运行结果:

elasticsearchClient = co.elastic.clients.elasticsearch.ElasticsearchClient@7945b206

2、创建索引

@SpringBootTest
class ElasticsearchStudyApplicationTests {

    private RestClient restClient;
    private ElasticsearchClient elasticsearchClient;
    @BeforeEach
    void ElasticsearchClientBuild(){
        // Create the low-level client
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200)).build();

        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        elasticsearchClient = new ElasticsearchClient(transport);
    }

    @Test
    void createIndex() throws IOException {
        Map<String, Property> documentMap = new HashMap<>();
        documentMap.put("userName", Property.of(property ->
                property.text(TextProperty.of(textProperty ->
                        textProperty.index(true).analyzer("ik_max_word"))
                    )
                )
        );
        documentMap.put("age", Property.of(property ->
                property.integer(IntegerNumberProperty.of(integerNumberProperty
                        -> integerNumberProperty.index(true))
                )
            )
        );


        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexBuilder ->
                createIndexBuilder.index("user").mappings(mappings ->
                        mappings.properties(documentMap))
                        .aliases("User",aliases ->
                                aliases.isWriteIndex(true))
        );
        Boolean acknowledged = createIndexResponse.acknowledged();
        System.out.println("acknowledged = " + acknowledged);
    }

    @AfterEach
    void ElasticsearchClientDestroy () throws IOException {
        restClient.close();
    }

}

运行结果:

acknowledged = true

使用 Kibana 查看索引情况

GET /_cat/indices?v
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size
green  open   user       IigagimERHOC_EiSX4p-zA   1   1          0            0       225b           225b

索引创建成功

索引结构:

GET /user
{
  "user" : {
    "aliases" : {
      "User" : {
        "is_write_index" : true
      }
    },
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "integer"
        },
        "userName" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        }
      }
    },
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "user",
        "creation_date" : "1649499106631",
        "number_of_replicas" : "1",
        "uuid" : "IigagimERHOC_EiSX4p-zA",
        "version" : {
          "created" : "8010199"
        }
      }
    }
  }
}

2、删除索引

@SpringBootTest
class ElasticsearchStudyApplicationTests {

    private RestClient restClient;
    private ElasticsearchClient elasticsearchClient;
    @BeforeEach
    void ElasticsearchClientBuild(){
        // Create the low-level client
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200)).build();

        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        elasticsearchClient = new ElasticsearchClient(transport);
    }

    @Test
    void deleteIndex() throws IOException {
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(index
                -> index.index("user")
        );
        boolean acknowledged = deleteIndexResponse.acknowledged();
        System.out.println("acknowledged = " + acknowledged);
    }
    @AfterEach
    void ElasticsearchClientDestroy () throws IOException {
        restClient.close();
    }
}

z

acknowledged = true

使用 Kibana 查看索引情况

GET /_cat/indices?v
health status index      uuid                   pri rep docs.count docs.deleted store.size pri.store.size

索引删除成功

3、查看索引信息

@SpringBootTest
class ElasticsearchStudyApplicationTests {

    private RestClient restClient;
    private ElasticsearchClient elasticsearchClient;
    @BeforeEach
    void ElasticsearchClientBuild(){
        // Create the low-level client
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200)).build();

        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        elasticsearchClient = new ElasticsearchClient(transport);
    }

    @Test
    void getIndex() throws IOException {
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(getIndex
                -> getIndex.index("user"));
        Map<String, IndexState> result = getIndexResponse.result();
        result.forEach((k, v) -> System.out.println("key = " + k + ", value = " + v));
    }

    @AfterEach
    void ElasticsearchClientDestroy () throws IOException {
        restClient.close();
    }
}

运行结果:

key = user, value = co.elastic.clients.elasticsearch.indices.IndexState@2afdf6b7

4、查看所有索引信息

@SpringBootTest
class ElasticsearchStudyApplicationTests {

    private RestClient restClient;
    private ElasticsearchClient elasticsearchClient;
    private ElasticsearchTransport transport;
    @BeforeEach
    void ElasticsearchClientBuild(){
        // Create the low-level client
        restClient = RestClient.builder(
                new HttpHost("127.0.0.1", 9200)).build();

        // Create the transport with a Jackson mapper
        transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());

        // And create the API client
        elasticsearchClient = new ElasticsearchClient(transport);
    }

    @Test
    void getAllIndex() throws IOException {
        IndicesResponse indicesResponse = elasticsearchClient.cat().indices();
        indicesResponse.valueBody().forEach(info -> System.out.println("info = " + info.health() + "\t"+  info.status() + "\t" + info.index() + "\t" + info.uuid() +"\t" + info.pri() + "\t" + info.rep() + "\t" + info.docsCount()));
    }

    @AfterEach
    void ElasticsearchClientDestroy () throws IOException {
        transport.close();
        restClient.close();
    }
}

运行结果:

info = yellow	open	crate_test	PEEVMOBES3K9Czfx00Yahg	1	1	0
info = yellow	open	good_spu	wWBCUiJPRmCGcQYUqTEFLA	1	1	0
info = yellow	open	user	LYj7ZSfDSeaVrmSpNT8zng	1	1	0
info = yellow	open	good	zDho1R2LRAKsdc8LPrQE8w	1	1	9

上一篇:Elasticsearch 相关软件安装

下一篇:SpringBoot 整合 Elasticsearch8(最新API——Java API Client for Elasticsearch)—— 2、文档操作