一 引入依赖
引入elasticsearch依赖
1 | <dependency> |
二 配置
配置如下参数
1 | elasticsearch: |
创建配置类如下
1 |
|
此时已经可以注入ElasticsearchRestTemplate进行操作
1 |
|
三 ElasticsearchRepository的使用
创建测试用实体类如下
1 |
|
ik分词器枚举类
1 | public class FieldAnalyzer { |
创建Repository类继承ElasticsearchRepository
其中泛型Integer为实体类中 ID 主键的类型
1 |
|
测试类如下
1 |
|
四 基于方法名查询
在 Spring Data 中,支持根据方法名作生成对应的查询(WHERE
)条件,进一步简化使用 JPA
具体是方法名以 findBy
、existsBy
、countBy
、deleteBy
开头,后面跟具体的条件。
规则参考 《Spring Data JPA —— Query Creation》 文档
具体如下
关键字 | 方法示例 | JPQL snippet |
---|---|---|
And |
findByLastnameAndFirstname |
… where x.lastname = ?1 and x.firstname = ?2 |
Or |
findByLastnameOrFirstname |
… where x.lastname = ?1 or x.firstname = ?2 |
Is , Equals |
findByFirstname ,findByFirstnameIs ,findByFirstnameEquals |
… where x.firstname = ?1 |
Between |
findByStartDateBetween |
… where x.startDate between ?1 and ?2 |
LessThan |
findByAgeLessThan |
… where x.age < ?1 |
LessThanEqual |
findByAgeLessThanEqual |
… where x.age <= ?1 |
GreaterThan |
findByAgeGreaterThan |
… where x.age > ?1 |
GreaterThanEqual |
findByAgeGreaterThanEqual |
… where x.age >= ?1 |
After |
findByStartDateAfter |
… where x.startDate > ?1 |
Before |
findByStartDateBefore |
… where x.startDate < ?1 |
IsNull , Null |
findByAge(Is)Null |
… where x.age is null |
IsNotNull , NotNull |
findByAge(Is)NotNull |
… where x.age not null |
Like |
findByFirstnameLike |
… where x.firstname like ?1 |
NotLike |
findByFirstnameNotLike |
… where x.firstname not like ?1 |
StartingWith |
findByFirstnameStartingWith |
… where x.firstname like ?1 (parameter bound with appended % ) |
EndingWith |
findByFirstnameEndingWith |
… where x.firstname like ?1 (parameter bound with prepended % ) |
Containing |
findByFirstnameContaining |
… where x.firstname like ?1 (parameter bound wrapped in % ) |
OrderBy |
findByAgeOrderByLastnameDesc |
… where x.age = ?1 order by x.lastname desc |
Not |
findByLastnameNot |
… where x.lastname <> ?1 |
In |
findByAgeIn(Collection ages) |
… where x.age in ?1 |
NotIn |
findByAgeNotIn(Collection ages) |
… where x.age not in ?1 |
True |
findByActiveTrue() |
… where x.active = true |
False |
findByActiveFalse() |
… where x.active = false |
IgnoreCase |
findByFirstnameIgnoreCase |
… where UPPER(x.firstame) = UPPER(?1) |
如果有排序需求,可以使用 OrderBy
关键字
1 示例repository
创建ProductRepository02Test
1 | public interface ProductRepository02 extends ElasticsearchRepository<ESProductDO, Integer> { |
对于分页操作,需要使用到 Pageable 参数,需要作为方法的最后一个参数
2 测试
1 |
|
四 ElasticsearchRestTemplate的使用
待补充