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

相关推荐
tachibana21 小时前
hot100 课程表(207)
java·数据结构·算法·leetcode
神仙别闹1 小时前
编写基于C++ Huffman 算法的无损压缩程序和解压程序
java·c++·算法
Elasticsearch1 小时前
从多模态 LLM 中引导构建音频嵌入
elasticsearch
IT乐手1 小时前
Android 写本地日志工具类
android·java
凤山老林2 小时前
ORM 框架性能调优:Spring Boot 下 N+1 查询根因治理、动态 SQL 优化与 Fetch 策略实战
数据库·spring boot·sql
阿维的博客日记2 小时前
spring里面的@RequestParam什么意思
java·后端·spring
laowangpython2 小时前
昆仑通态 Mcgs Pro软件安装步骤(附安装包)Mcgs Pro 3.3.6 下载安装教程(保姆级)
java·服务器·数据库·其他
是梦终空2 小时前
计算机毕业设计279—基于SpringBoot+Vue3校园商户意见反馈系统(源代码+数据库+17000字论文+ppt)
数据库·spring boot·vue·毕业设计·课程设计·毕业论文·源代码
罗超驿2 小时前
6.Java LinkedList深度解析:从链表原理到源码实践
java·开发语言·链表
2501_948106912 小时前
计算机毕业设计之jsp物业管理系统
java·大数据·开发语言·汽车·课程设计