Spring Boot 整合 Elasticsearch

Spring Boot 整合 Elasticsearch 技术文档

1. 环境准备

1.1 依赖配置

xml 复制代码
<!-- Spring Boot Starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- Elasticsearch High-Level Client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.10.1</version>
</dependency>

<!-- Spring Boot Elasticsearch Starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2. 核心概念解析

2.1 客户端类型对比

客户端类型 特点说明 适用场景
Low-Level Client 原生API,版本同步性差 需要深度定制化操作
High-Level Client 与ES版本同步更新,封装更完善 通用场景推荐使用

2.2 版本兼容性

  • Spring Boot 2.x 默认使用 Low-Level Client
  • High-Level Client 需要手动配置,版本需与ES保持一致
  • 推荐使用 Elasticsearch 8.x 版本

3. 高级客户端配置

3.1 客户端初始化

java 复制代码
// 创建RestClient构建器
RestClientBuilder builder = RestClient.builder(
    new HttpHost("localhost", 9200, "http")
);

// 初始化客户端
RestHighLevelClient client = new RestHighLevelClient(builder);

3.2 配置文件设置

yaml 复制代码
elasticsearch:
  host: localhost
  port: 9200
  cluster-name: my-cluster

4. 索引操作实现

4.1 索引创建

java 复制代码
// 创建索引请求对象
CreateIndexRequest request = new CreateIndexRequest("books");

// 设置索引参数
request.settings(Settings.builder()
    .put("index.number_of_shards", 3)
    .put("index.number_of_replicas", 1));

// 执行创建操作
client.indices().create(request, RequestOptions.DEFAULT);

4.2 索引删除

java 复制代码
// 删除索引
client.indices().delete(new DeleteIndexRequest("books"), RequestOptions.DEFAULT);

5. 测试用例设计

5.1 测试方法封装

java 复制代码
@BeforeEach
void setUp() throws Exception {
    // 初始化客户端
    client = new RestHighLevelClient(RestClient.builder(
        new HttpHost("localhost", 9200, "http")
    ));
}

@AfterEach
void tearDown() throws Exception {
    // 关闭客户端
    client.close();
}

5.2 操作流程示例

java 复制代码
@Test
void testCreateIndex() throws IOException {
    // 创建索引
    CreateIndexRequest request = new CreateIndexRequest("test_index");
    client.indices().create(request, RequestOptions.DEFAULT);
    
    // 验证索引是否存在
    assertTrue(client.indices().exists(new IndexRequest("test_index"), RequestOptions.DEFAULT));
    
    // 删除索引
    client.indices().delete(new DeleteIndexRequest("test_index"), RequestOptions.DEFAULT);
}

6. 常见问题与解决方案

6.1 客户端管理注意事项

  • 资源释放:确保每次操作后关闭客户端,避免内存泄漏
  • 异常处理:添加try-catch块捕获ElasticsearchException
  • 版本兼容:确认ES版本与客户端版本匹配

6.2 配置优化建议

  • 使用RestClient.builder()构建器配置连接参数
  • 启用连接池提升性能
  • 配置超时时间防止阻塞

7. 进阶操作指南

7.1 分词器配置

java 复制代码
// 设置分析器
request.settings(Settings.builder()
    .put("index.analysis.analyzer.custom.type", "custom")
    .put("index.analysis.analyzer.custom.tokenizer", "standard")
    .put("index.analysis.analyzer.custom.filter", "lowercase"));

7.2 索引映射定义

java 复制代码
// 定义映射结构
request.mapping(Maps.of(
    "properties", Maps.of(
        "title", Maps.of("type", "text"),
        "author", Maps.of("type", "keyword")
    )
));

8. 性能优化建议

  1. 启用连接池配置:
java 复制代码
RestClient.builder(new HttpHost("localhost", 9200, "http"))
    .setHttpClientConfigCallback(httpClientBuilder -> {
        HttpClientBuilder cb = HttpClientBuilder.create()
            .setMaxConnTotal(100)
            .setMaxConnPerRoute(20);
        return cb;
    });
  1. 合理设置分片数量:
  • 数据量 < 10GB:1个主分片
  • 数据量 10-100GB:3个主分片
  • 数据量 >100GB:5-7个主分片
  1. 使用批量操作提升效率:
java 复制代码
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("books").source(
    "title", "Spring Boot实战",
    "author", "张三"
));
request.add(new IndexRequest("books").source(
    "title", "Elasticsearch深度解析",
    "author", "李四"
));
client.bulk(request, RequestOptions.DEFAULT);

9. 版本升级注意事项

  • 从7.x升级到8.x需注意:
    1. 客户端API变更
    2. 分片管理方式调整
    3. 查询DSL语法更新
    4. 索引生命周期管理(Lifecycle)变化

10. 参考资料

本文档基于Elasticsearch 8.x和Spring Boot 2.7.x版本编写,实际使用时请根据具体版本调整配置参数。

相关推荐
桦说编程1 小时前
深入解析CompletableFuture源码实现(2)———双源输入
java·后端·源码
舒一笑2 小时前
大模型时代的程序员成长悖论:如何在AI辅助下不失去竞争力
后端·程序员·掘金技术征文
lang201509282 小时前
Spring Boot优雅关闭全解析
java·spring boot·后端
小羊在睡觉2 小时前
golang定时器
开发语言·后端·golang
用户21411832636023 小时前
手把手教你在魔搭跑通 DeepSeek-OCR!光学压缩 + MoE 解码,97% 精度还省 10-20 倍 token
后端
追逐时光者3 小时前
一个基于 .NET 开源、功能强大的分布式微服务开发框架
后端·.net
刘一说3 小时前
Spring Boot 启动慢?启动过程深度解析与优化策略
java·spring boot·后端
壹佰大多3 小时前
【spring如何扫描一个路径下被注解修饰的类】
java·后端·spring
间彧3 小时前
Java双亲委派模型的具体实现原理是什么?
后端
间彧3 小时前
Java类的加载过程
后端