SpringBoot整合elasticsearch-java

一、依赖

系统使用的是ElasticSearch8.2.0

java 复制代码
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.1.0</version>
</dependency>

二、配置

1、yml文件配置

java 复制代码
elasticsearch:
  url: 192.168.58.131
  port: 9200

2、config配置文件

java 复制代码
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class RestClientConfig {
    @Value("${elasticsearch.url}")
    private String url;

    @Value("${elasticsearch.port}")
    private String port;

    @Bean
    public ElasticsearchClient elasticsearchClient() throws IOException {
        // 创建低级客户端
        RestClient restClient = RestClient.builder(
                new HttpHost(url, Integer.parseInt(port))
        ).build();

        // 使用 Jackson 映射器创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper()
        );

        // 创建 API 客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);

        // 关闭 ES 客户端
        transport.close();
        restClient.close();

        return client;
    }
}

3、测试是否连接成功

java 复制代码
@SpringBootTest
class ElasticSearchApplicationTests {
    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Test
    void test(){
        System.out.println(elasticsearchClient);

    }
}

运行成功

三、索引基本语法

参考文档:Elasticsearch8.x版本中RestHighLevelClient被弃用,新版本中全新的Java客户端Elasticsearch Java API Client中常用API练习

相关推荐
用户3721574261351 小时前
Java 批量操作 Excel 超链接:添加、读取、修改和删除
java
用户3721574261352 小时前
Java 将 Excel 图表导出为图片:指定图表、批量导出与图表工作表
java
这个昵称不容易3 小时前
交流论坛网站设计与实现:SpringBoot 论坛 130 个接口,附论文与运行截图
java·springboot·毕设
秋天的怀念_David4 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
apcipot_rain4 小时前
C++转java日记(13)
java·开发语言
CoderYanger6 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
飞奔的瓜牛6 小时前
Elasticsearch 日常巡检清单与实战避坑指南
大数据·elasticsearch·搜索引擎
CoderYanger7 小时前
Java EE 进阶:12.Spring AOP(第一弹)
java·开发语言·spring boot·后端·spring·java-ee·交互
H H.7 小时前
Java笔记:String字符串
java·开发语言·经验分享·笔记·其他