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版本编写,实际使用时请根据具体版本调整配置参数。

相关推荐
㳺三才人子2 小时前
初探 Flask
后端·python·flask·html
星栈独行2 小时前
我在 Rust 全栈项目里用 JWT 做无状态认证
开发语言·后端·rust·前端框架·开源·github·web
Java爱好狂.2 小时前
Java程序员体系化学习路线(2026最新版)
java·后端·java面试·java架构师·java程序员·java八股文·java学习路线
陈随易3 小时前
Redis 8.8发布,一定要更新
前端·后端·程序员
装不满的克莱因瓶3 小时前
SpringBoot 如何将 lib 目录中jar包打包进最终的jar包里面
spring boot·后端·maven·jar·mvn
ltl4 小时前
Transformer 原论文实验结果:为什么 28.4 BLEU 足以改写路线图
后端
excel4 小时前
为什么我推荐使用 Termius:现代 SSH 工具的完整体验
前端·后端
卷毛的技术笔记5 小时前
Java后端硬核实战:用Spring AI Alibaba+Redis给LLM装上“超强记忆中枢”
java·人工智能·redis·后端·spring·ai·系统架构
IT_陈寒6 小时前
Java的Optional差点让我掉坑里,这几个坑你别踩
前端·人工智能·后端
子兮曰6 小时前
Harness 驾驭工程深度教程:从 AGENTS.md 到全链路 AI 编码基础设施
前端·后端·ai编程