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

相关推荐
weixin_4896900214 小时前
【IDEA 2025.2.4】 Maven 仅能手动 Reload All Maven Projects 问题解决
java·maven·intellij-idea
雨辰AI14 小时前
MySQL 迁移至达梦 DM9 完整改造指南|99% SQL 零改动
java·开发语言·数据库·sql·mysql·政务
golang学习记14 小时前
Intellij IDEA 2026重磅更新!开发体验大升级
java·ide·intellij-idea
弹简特14 小时前
【Java项目-轻聊】05-AI赋能设计接口文档
java·开发语言
达达爱吃肉14 小时前
claude 接入deepseek 运行报错
java·服务器·前端
OctShop大型商城源码14 小时前
OctShop对比JAVA商城源码_OctShop大型专业级多用户商城源码
java·开发语言·商城系统·小程序商城·octshop
guslegend14 小时前
AGENT.md,Skill与工程规范
java·开发语言·数据库
周末也要写八哥14 小时前
C++中单线程方式之无脑上锁
java·开发语言·c++
Reisentyan14 小时前
[Advance]GoLang Learn Data Day 4
java·数据库·golang
MaCa .BaKa14 小时前
55-宠物爱心救助领养系统-宠物救助领养系统
java·vue.js·tomcat·maven·springboot·宠物救助领养系统