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

相关推荐
今天AI了吗几秒前
Hermes Agent 搭建全流程:从本机试跑到可持续运行的个人 AI Agent
java·人工智能·python·学习·embedding
春卷同学8 分钟前
032-关系型数据库在记账应用中的建模与查询优化
java·jvm·数据库
不平衡的叉叉树24 分钟前
Springboot+Mockito简单使用单元测试
java·spring boot·单元测试
空中湖25 分钟前
Spring AI 多模型接入实战:OpenAI、Ollama、通义千问切换只需改配置
java·人工智能·spring
tianyatest28 分钟前
表格分类统计及排序
java·excel·暖通
山东点狮信息科技有限公司32 分钟前
企业级开源OA系统推荐
vue.js·spring boot·性能优化·系统架构·开源
万亿少女的梦1681 小时前
基于Spring Boot与MySQL的乡镇群众服务系统设计与实现
java·spring boot·mysql·权限管理·前后端分离
thefool1122661 小时前
Java 面向对象
java
2501_948106911 小时前
计算机毕业设计之jsp-智慧旅游分享平台
java·开发语言·spark·汽车·课程设计·旅游
阿里云云原生1 小时前
Agent 不再是“玩具”!AgentScope Java 2.0 GA 发布:构建企业级分布式智能体底座
java·开发语言·分布式·agentscope