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练习

相关推荐
hai_android6 分钟前
Android 设备锁定:Kiosk Mode 实战
android·java·android jetpack
张伯毅14 分钟前
External Shuffle Service(spark3_shuffle):原理、配置与排障
java·开发语言·spark·yarn
Elasticsearch16 分钟前
控制告警如何触发、恢复和发送通知:Elastic 可观测性中的 Kibana 通用告警
elasticsearch
high一马平川38 分钟前
# SystemUI Dagger2 精读 · 第 2 章 @Inject:1200 处构造注入,和 1 处例外
android·java·kotlin
小陈从不会敲代码39 分钟前
JavaEE面试复习(多线程-初阶)
java·面试·java-ee
周厉40 分钟前
酒店PMS系统设计:房型房价管理与动态价格优先级实现(Java/MySQL)
java·数据库·pms酒店系统
一碗白开水一1 小时前
Day 5 · 弹性 | 微观
java·前端·数据库
迪飞特科技1 小时前
大模型接入业务系统:API、本地部署、RAG、智能体四种路线怎么选
java·数据库·人工智能·知识图谱·deepseek·本地化大模型
vipxieliang1 小时前
ValidX 验证器缓存机制:如何提升验证性能
java·spring boot
未秃头的程序猿1 小时前
Spring Cloud Gateway 做统一加解密,我在请求体上栽了三天
java·后端·架构