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

相关推荐
dreamxian9 分钟前
苍穹外卖day09
java·spring boot·tomcat·log4j·maven
AMoon丶12 分钟前
Golang--内存管理
开发语言·后端·算法·缓存·golang·os
zabr25 分钟前
花了 100+ 篇笔记,我整理出 了一套 AI Agent 工程完全指南
前端·后端·agent
神奇小汤圆38 分钟前
Java面试题及答案整理(2026年金三银四最新版,持续更新)
后端
uzong41 分钟前
“腾讯QClaw全面开放”,不花 Token 钱、真正体验一把小龙虾的快乐,最低成本全面了解龙虾
人工智能·后端
楼田莉子42 分钟前
C++高并发内存池:内存池调优与测试
c++·后端·哈希算法·visual studio
短剑重铸之日1 小时前
《ShardingSphere解读》16 改写引擎:如何理解装饰器模式下的 SQL 改写实现机制?
java·数据库·后端·sql·shardingsphere·分库分表·装饰器模式
q5431470871 小时前
VScode 开发 Springboot 程序
java·spring boot·后端
学习要积极1 小时前
Springboot图片验证码-EasyCaptcha
java·spring boot·后端
Nyarlathotep01131 小时前
可重入锁ReentrantLock基础和原理
后端