第一部分:elasticsearch 简介
1. 什么是 elasticsearch?
elasticsearch 是一个基于 apach立即掌握elasticsearch+spring实战整合,告别mysql模糊查询性能瓶颈,本文从核心概念到repository封装,带你快速实现高性能全文检索与复杂聚合分析,附版本兼容避坑指南e lucene 构建的分布式、restful 风格的搜索和数据分析引擎。它通常被用来替代传统数据库(如 mysql)在模糊查询、全文检索、多维度筛选等场景下的不足。
2. 核心概念(与关系型数据库对比)
为了方便理解,我们可以将其与 mysql 进行类比:
| elasticsearch | 关系型数据库 | 说明 |
|---|---|---|
| index (索引) | database (数据库) | es 7.x 之后,index 更像一张表,但在逻辑上相当于数据库。 |
| type (类型) | table (表) | es 7.x 之后已弱化,一个 index 只对应一个 type,通常不再提及。 |
| document (文档) | row (行/记录) | es 存储数据的单元,通常是 json 格式。 |
| field (字段) | column (列) | 文档中的属性。 |
| mapping (映射) | schema (表结构) | 定义字段名称、类型(text, keyword, integer等)等约束。 |
| dsl (查询语言) | sql | es 使用 json 格式的 dsl 进行查询。 |
3. 为什么使用 es?
- 极致的搜索速度:基于倒排索引,毫秒级响应。
- 模糊查询与分词:支持中文分词(如 ik 分词器),能实现“搜索‘苹果’能找到‘苹果手机’”的效果。
- 高性能聚合分析:适合做报表、统计分析。
第二部分:在 spring 项目中的使用方法
在 spring boot 项目中,主要有两种主流的使用方式:
- spring data elasticsearch(推荐):spring 官方封装,类似 jpa,提供 repository 接口,开发效率高。
- elasticsearch java api client:es 官方提供的原生客户端,灵活性高,适合复杂查询。
以下以 spring boot 2.7.x / 3.x + spring data elasticsearch 为例进行演示。
1. 环境准备
确保本地或服务器已安装 elasticsearch(建议版本 7.x 或 8.x)。
2. 引入依赖
在 pom.xml 中添加依赖(版本需与安装的 es 版本对应):
<!-- spring boot starter data elasticsearch -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-elasticsearch</artifactid>
</dependency>
<!-- lombok (用于简化代码) -->
<dependency>
<groupid>org.projectlombok</groupid>
<artifactid>lombok</artifactid>
<optional>true</optional>
</dependency>
3. 配置连接
在 application.yml 中配置 es 的地址和端口:
spring:
elasticsearch:
uris: http://localhost:9200 # es 地址
# username: elastic # 如果开启了安全认证
# password: your_password
4. 定义实体类
使用 @document 注解映射索引,@field 注解定义字段属性。
import lombok.data;
import org.springframework.data.annotation.id;
import org.springframework.data.elasticsearch.annotations.document;
import org.springframework.data.elasticsearch.annotations.field;
import org.springframework.data.elasticsearch.annotations.fieldtype;
@data
@document(indexname = "product_index") // 索引名称,类似于表名
public class product {
@id
private long id; // 主键
@field(type = fieldtype.text, analyzer = "ik_max_word") // 文本类型,指定分词器
private string name;
@field(type = fieldtype.keyword) // 关键字类型,不分词,精确匹配
private string category;
@field(type = fieldtype.double)
private double price;
@field(type = fieldtype.text)
private string description;
}
5. 定义 repository 接口
继承 elasticsearchrepository,即可获得基本的 crud 和简单查询能力。
import org.springframework.data.elasticsearch.repository.elasticsearchrepository;
import org.springframework.stereotype.repository;
import java.util.list;
@repository
public interface productrepository extends elasticsearchrepository<product, long> {
// 方法命名规则查询 (自动实现)
// 查询指定分类下的商品
list<product> findbycategory(string category);
// 价格范围查询
list<product> findbypricebetween(double min, double max);
}
6. 业务层使用示例
基本 crud 操作:
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import java.util.list;
import java.util.optional;
@service
public class productservice {
@autowired
private productrepository productrepository;
// 1. 新增/修改文档
public void saveproduct() {
product product = new product();
product.setid(1l);
product.setname("苹果手机 iphone 15");
product.setcategory("手机");
product.setprice(6999.00);
productrepository.save(product); // 自动生成索引和文档
}
// 2. 查询单个
public product getproduct(long id) {
optional<product> product = productrepository.findbyid(id);
return product.orelse(null);
}
// 3. 简单条件查询
public list<product> getbycategory() {
return productrepository.findbycategory("手机");
}
}
复杂查询:
对于复杂的业务查询(如组合条件、高亮显示、分页排序),我们需要使用 elasticsearchresttemplate 或 criteria api。
import org.springframework.data.elasticsearch.core.elasticsearchresttemplate;
import org.springframework.data.elasticsearch.core.searchhit;
import org.springframework.data.elasticsearch.core.searchhits;
import org.springframework.data.elasticsearch.core.query.criteria;
import org.springframework.data.elasticsearch.core.query.criteriaquery;
import org.springframework.data.elasticsearch.core.query.query;
import java.util.list;
import java.util.stream.collectors;
@service
public class productsearchservice {
@autowired
private elasticsearchresttemplate elasticsearchtemplate;
// 复杂查询示例:搜索名字包含关键词且价格在范围内的商品
public list<product> searchproducts(string keyword, double minprice, double maxprice) {
// 1. 构建查询条件
criteria criteria = criteria.where("name").contains(keyword)
.and("price").between(minprice, maxprice);
// 2. 构建查询对象
query query = new criteriaquery(criteria);
// 3. 执行查询
searchhits<product> searchhits = elasticsearchtemplate.search(query, product.class);
// 4. 转换结果
return searchhits.stream()
.map(searchhit::getcontent)
.collect(collectors.tolist());
}
}
7. 高级用法:原生 dsl 查询
如果 spring data 的封装无法满足需求,你可以使用 nativequery 直接构建 es 的 dsl json 查询:
import org.springframework.data.elasticsearch.core.query.nativequery;
import org.elasticsearch.index.query.querybuilders; // 注意导入包
public list<product> nativesearch(string name) {
// 使用 querybuilders 构建原生 elasticsearch 查询条件
nativequery query = nativequery.builder()
.withquery(querybuilders.matchquery("name", name))
.withpageable(pagerequest.of(0, 10)) // 分页
.build();
searchhits<product> hits = elasticsearchtemplate.search(query, product.class);
return hits.stream().map(searchhit::getcontent).collect(collectors.tolist());
}
总结
- 定位:elasticsearch 是解决“搜索”和“模糊查询”的神器,是对传统数据库的性能补充。
- spring 整合:
- 定义实体类使用
@document映射索引。 - 继承
elasticsearchrepository实现快速 crud。 - 注入
elasticsearchresttemplate处理复杂查询。
- 定义实体类使用
- 注意点:
- 版本兼容性:spring boot 版本与 es 版本有严格的对应关系,版本不匹配会导致连接失败。
- 映射设计:es 不支持多表关联,设计索引时通常采用“宽表”模式,即把需要展示的数据都冗余在一条文档中。
到此这篇关于在spring项目里使用elasticsearch的方法的文章就介绍到这了,更多相关spring项目使用elasticsearch内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论