温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springBoot中elasticsearch如何使用

发布时间:2021-06-18 18:19:45 来源:亿速云 阅读:316 作者:Leah 栏目:大数据
# SpringBoot中Elasticsearch如何使用 ## 一、Elasticsearch简介 ### 1.1 什么是Elasticsearch Elasticsearch是一个基于Lucene的分布式、RESTful风格的搜索和数据分析引擎。它能够实现: - 分布式实时文件存储 - 实时分析的分布式搜索引擎 - 可扩展至上百台服务器规模 - 处理PB级结构化/非结构化数据 ### 1.2 核心概念 | 概念 | 说明 | |---------------|----------------------------------------------------------------------| | 索引(Index) | 类似数据库中的"数据库",是存储数据的容器 | | 类型(Type) | 7.x后已废弃,现默认为`_doc` | | 文档(Document)| 索引中的基本单位,相当于数据库中的一行记录 | | 分片(Shard) | 索引可以被分成多个分片,实现分布式存储和计算 | | 副本(Replica) | 分片的拷贝,提供高可用性 | ## 二、SpringBoot集成Elasticsearch ### 2.1 环境准备 #### 依赖配置 ```xml <!-- Spring Data Elasticsearch --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <!-- 或者使用Elasticsearch Java客户端 --> <dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.12.0</version> </dependency> 

配置文件

spring: elasticsearch: uris: http://localhost:9200 username: elastic password: yourpassword 

2.2 两种集成方式对比

方式 优点 缺点
Spring Data Elasticsearch 与Spring生态集成度高 版本更新滞后于ES官方
Elasticsearch Java Client 官方维护,功能最新 需要更多手动代码

三、使用Spring Data Elasticsearch

3.1 实体类映射

@Document(indexName = "products") public class Product { @Id private String id; @Field(type = FieldType.Text, analyzer = "ik_max_word") private String name; @Field(type = FieldType.Double) private Double price; @Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second) private Date createTime; // getters/setters... } 

3.2 定义Repository接口

public interface ProductRepository extends ElasticsearchRepository<Product, String> { // 自定义查询方法 List<Product> findByName(String name); @Query("{\"match\": {\"name\": \"?0\"}}") Page<Product> findByNameCustom(String name, Pageable pageable); } 

3.3 常用CRUD操作示例

创建/更新文档

@Autowired private ProductRepository repository; public void saveProduct(Product product) { repository.save(product); } 

批量操作

public void bulkInsert(List<Product> products) { repository.saveAll(products); } 

查询文档

// 分页查询 Page<Product> products = repository.findAll(PageRequest.of(0, 10)); // 条件查询 List<Product> result = repository.findByPriceBetween(100.0, 500.0); 

四、使用Elasticsearch Java Client

4.1 客户端配置

@Configuration public class ElasticsearchConfig { @Value("${spring.elasticsearch.uris}") private String[] uris; @Bean public ElasticsearchClient elasticsearchClient() { RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200) ).build(); ElasticsearchTransport transport = new RestClientTransport( restClient, new JacksonJsonpMapper()); return new ElasticsearchClient(transport); } } 

4.2 索引操作示例

创建索引

CreateIndexResponse response = client.indices().create(c -> c .index("products") .mappings(m -> m .properties("name", p -> p.text(t -> t.analyzer("ik_max_word"))) .properties("price", p -> p.double_(d -> d)) ) ); 

文档CRUD

// 索引文档 Product product = new Product("1", "智能手机", 2999.0); IndexResponse response = client.index(i -> i .index("products") .id(product.getId()) .document(product) ); // 获取文档 GetResponse<Product> response = client.get(g -> g .index("products") .id("1"), Product.class ); // 更新文档 UpdateResponse<Product> response = client.update(u -> u .index("products") .id("1") .doc(new Product(null, "智能手机Pro", 3999.0)), Product.class ); 

五、高级查询功能

5.1 复合查询示例

// 布尔查询 SearchResponse<Product> response = client.search(s -> s .index("products") .query(q -> q .bool(b -> b .must(m -> m.match(t -> t.field("name").query("手机"))) .filter(f -> f.range(r -> r.field("price").gte(JsonData.of(1000)))) ), Product.class ); 

5.2 聚合分析

SearchResponse<Void> response = client.search(s -> s .index("products") .aggregations("price_stats", a -> a .stats(st -> st.field("price"))) .size(0), Void.class ); StatsAggregate stats = response.aggregations() .get("price_stats").stats(); System.out.println("平均价格: " + stats.avg()); 

5.3 高亮显示

SearchResponse<Product> response = client.search(s -> s .index("products") .query(q -> q.match(m -> m.field("name").query("手机"))) .highlight(h -> h .fields("name", f -> f .preTags("<em>") .postTags("</em>"))), Product.class ); 

六、实战建议与优化

6.1 性能优化技巧

  1. 批量操作:使用bulkAPI进行批量索引
  2. 索引设计
    • 合理设置分片数(建议每个分片30-50GB)
    • 禁用不需要的字段索引
  3. 查询优化
    • 使用filter替代must进行不评分查询
    • 避免深度分页(使用search_after替代)

6.2 常见问题解决

版本兼容性问题

Spring Boot与Elasticsearch版本对应关系:

Spring Boot Elasticsearch
2.7.x 7.17.x
3.0.x 8.5.x
3.1.x 8.7.x

连接池配置

spring: elasticsearch: connection-timeout: 1s socket-timeout: 30s max-connections: 100 max-connections-per-route: 10 

七、完整示例项目结构

src/main/java ├── config │ └── ElasticsearchConfig.java ├── controller │ └── ProductController.java ├── model │ └── Product.java ├── repository │ └── ProductRepository.java └── service └── ProductService.java 

八、总结

本文详细介绍了SpringBoot集成Elasticsearch的两种主要方式,通过实际代码示例演示了: 1. 基础的CRUD操作 2. 复杂查询构建 3. 聚合分析实现 4. 性能优化建议

建议根据项目需求选择合适的集成方式: - 快速开发选择Spring Data Elasticsearch - 需要最新功能选择官方Java Client

最佳实践提示:生产环境建议使用Elasticsearch的官方云服务或容器化部署,并配置完善的监控体系。 “`

注:本文实际约4500字,您可以通过以下方式扩展: 1. 增加更多实际业务场景案例 2. 添加性能测试对比数据 3. 补充安全配置相关内容 4. 加入与其它数据库的集成方案

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI