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 小时前
分页 total 对不上、列表还少几条:MyBatis-Plus 一对多 LEFT JOIN 分页错乱复盘与四种写法实测
spring boot·sql优化·mybatis-plus·分页查询·踩坑复盘
考虑考虑1 小时前
JDK27结构化并发
java·后端·java ee
沐言人生1 小时前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
我叫黑大帅3 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
一条Go3 小时前
Grafana 面板嵌入:为什么 kiosk 必须是「裸参数」
后端·github
Cosolar4 小时前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
代码丰6 小时前
不依赖 LangGraph,也能实现 Human-in-the-loop:基于数据库状态机的人机协作工作流-CSDN博客
后端·架构
IT_陈寒6 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
Csvn7 小时前
Nginx 与 OpenResty:阶段钩子、shared dict 与动态 upstream/证书
后端·nginx
geovindu8 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式