您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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
方式 | 优点 | 缺点 |
---|---|---|
Spring Data Elasticsearch | 与Spring生态集成度高 | 版本更新滞后于ES官方 |
Elasticsearch Java Client | 官方维护,功能最新 | 需要更多手动代码 |
@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...
}
public interface ProductRepository extends ElasticsearchRepository<Product, String> {
// 自定义查询方法
List<Product> findByName(String name);
@Query("{\"match\": {\"name\": \"?0\"}}")
Page<Product> findByNameCustom(String name, Pageable pageable);
}
@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);
@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);
}
}
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))
)
);
// 索引文档
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
);
// 布尔查询
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
);
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());
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
);
bulk
API进行批量索引filter
替代must
进行不评分查询search_after
替代)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. 加入与其它数据库的集成方案
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。