我的 elasticsearch 服务版本为 7.17.13,所以 springboot 版本我选用 2.7.10
org.springframework.boot
spring-boot-dependencies
2.7.10
pom
import
客户端版本选择 springboot 默认版本
org.springframework.boot
spring-boot-starter-data-elasticsearch
添加配置文件
spring:
elasticsearch:
uris: http://localhost:9200
username: elastic
password: admin123
对应的配置类:org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties
ps: spring.elasticsearch.rest 的配置方式从 springboot 2.6.0 起已弃用,将在3.0.0中移除,不推荐使用
@Repository
public interface SystemConfigRepository extends ElasticsearchRepository {
SystemConfig findByBizAndCodeAndKey(String biz, String appCode, String ruleKey);
@Query("{\"bool\": {\"must\": [{\"match\": {\"appCode\": \"?0\"}}," +
"{\"match\": {\"ruleKey\": \"?1\"}}]}}")
SystemConfig findByCondition(String appCode, String ruleKey);
}
查询方法根据方法的命名自动生成,方法名中的关键字和字段名称将被解析为查询条件。 常用的命名约定如下:
findBy
、getBy
、queryBy
:表明查询方法的开始。- 属性名称:指定要匹配的字段名。
And
、Or
:用于连接多个条件。In
、NotIn
:用于查询字段值在给定集合中或不在给定集合中的记录。Is
、Equals
:用于查询字段是否等于给定值的记录。Like
:用于查询字段模糊匹配的记录。GreaterThan
、LessThan
:用于查询字段大于或小于给定值的记录。OrderBy
:用于指定排序字段
基于 @Query
注解在查询方法上直接指定 Elasticsearch 查询语句,可以使用 Elasticsearch 查询 DSL 编写复杂的查询逻辑,并使用 SpEL 表达式引用方法参数或其他变量。
@Query("{\"match\": {\"field\": \"value\"}}")
List findByCustomQuery();
@Query("{\"match\": {\"field\": \"?0\"}}")
List findByValue(String value);
// 使用布尔查询可以组合多个查询条件,例如 must、should、must_not 等
@Query("{\"bool\": {\"must\": [{\"match\": {\"field1\": \"value1\"}}," +
"{\"match\": {\"field2\": \"value2\"}}]}}")
List findByCustomQuery();
@Query("{\"range\": {\"age\": {\"gte\": 18, \"lte\": 30}}}")
List findByAgeRange();
@Query("{\"match_all\": {}}")
List findAllByOrderByFieldAsc();
@Resource
private ElasticsearchOperations esOperations;
public List getMonitorAppList() {
SystemConfig systemConfig = getAppInfo();
Criteria criteria = new Criteria(SystemConfig.BIZ).is(systemConfig.getBiz())
.and(SystemConfig.CODE).is(systemConfig.getCode())
.and(SystemConfig.STATUS).is(systemConfig.getStatus());
// 时间倒序
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
criteriaQuery.addSort(Sort.by(Sort.Direction.DESC,SystemConfig.CREATED_TIME));
SearchHits searchHits = esOperations.search(criteriaQuery, SystemConfig.class);
// 转换成 map
return searchHits.stream().map(searchHit -> {
SystemConfig systemConfigES = searchHit.getContent();
return new AppInfoBO(systemConfigES.getKey(), (String) systemConfigES.getValue());
}).collect(Collectors.toList());
}
至此执行单元测试即可完成