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

相关推荐
白狐_79837 分钟前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander2581 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅1 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
Elastic 中国社区官方博客3 小时前
Elasticsearch:使用 AI Agent 来创建 workflow
大数据·运维·人工智能·elasticsearch·搜索引擎·自动化·全文检索
极创信息3 小时前
系统安全隐患全方位排查方案:标准化渗透测试全流程
java·opencv·struts·数据挖掘·eclipse·语音识别·hibernate
阿里云大数据AI技术3 小时前
AI Search+ES 9.4.X最佳实践:“更快、更准、更安全的企业级搜索引擎”"为AI Agent提供坚实底座”
人工智能·elasticsearch·agent
汉字萌萌哒3 小时前
2019CCF-CSP入门级C++试题解析
java·开发语言·c++
喜欢的名字被抢了4 小时前
程序出问题怎么查,以及如何让它不掉线
java·运维·数据库
数据知道4 小时前
反序列化漏洞:Java、PHP、Python 三条线各讲透
java·网络·python·安全·网络安全·php
2601_949950635 小时前
Java 面试准备,用练题簿把“背过八股”变成“真正会答”
java·开发语言·面试·刷题·小程序推荐