打开pom文件,导入依赖
org.dromara.easy-es
easy-es-boot-starter
Latest Version
org.springframework.boot
spring-boot-starter-web
org.elasticsearch.client
elasticsearch-rest-high-level-client
org.elasticsearch
elasticsearch
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.14.0
org.elasticsearch
elasticsearch
7.14.0
查询某属性为指定列表内数据,以列表形式返回
public List selectAll(){
lambdaEsQueryWrapper wrapper = new lambdaEsQueryWrapper();
List nameList = new ArrayList<>();
nameList.add("name1");
nameList.add("name2");
// 查询AttackAlarm的name属性为name1或name2的数据
wrapper.in(AttackAlarm::getName,nameList);
List attackAlarmList = attackAlarmMapper.selectList(wrapper );
return attackAlarmList;
}
大小用于时间比较,需要给实体的属性添加注解
public class AttackAlarm{
// 将alarmId设置为唯一id
@IndexId(type = IdType.CUSTOMIZE)
@IndexField(value = "alarmId")
private String alarmId;
// 给时间属性添加索引,设置类型为DATE,可以指定日期格式
@IndexField(fieldType = FieldType.DATE, dateFormat = "yyyy-MM-dd")
private String eventTime;
}
添加注解后,查询时可直接使用ge、le、gt、lt比较时间参数
public List selectAll(){
lambdaEsQueryWrapper wrapper = new lambdaEsQueryWrapper();
wrapper.ge(AttackAlarm::getEventTime,"2023-09-15");
List attackAlarmList = attackAlarmMapper.selectList(wrapper);
return attackAlarmList;
}
easy-es有直接的API可以进行聚合查询,但是查询结果返回的json不太规范,需要逐步解析取值。
首先需要给要聚合的属性添加索引@IndexField(fieldType = FieldType.TEXT, fieldData = true),最好在索引刚建立之前就确定好,在建立索引之后,中途给属性添加注解有时会报错。
public class AttackAlarm{
// 将alarmId设置为唯一id
@IndexId(type = IdType.CUSTOMIZE)
@IndexField(value = "alarmId")
private String alarmId;
// 应用id,区分不同应用,添加索引,使其支持聚类
@IndexField(fieldType = FieldType.TEXT, fieldData = true)
private String appId;
// 给时间属性添加索引,设置类型为DATE,可以指定日期格式
@IndexField(fieldType = FieldType.DATE, dateFormat = "yyyy-MM-dd")
private String eventTime;
}
此时appId属性支持聚合查询,调用groupBy,必须使用SearchResponse来接收结果
lambdaEsQueryWrapper wrapper = new lambdaEsQueryWrapper();
wrapper.groupBy(AttackAlarm::getAppId);
SearchResponse response = attackAlarmMapper.search(wrapper);
接收到结果,是不太规范的json数据
"aggregations":{"sterms#creator":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[{"key":"111111111111","doc_count":2},{"key":"22222222222222","doc_count":1}]}}
其中,buckets为聚合之后的结果,key对应appId,doc_count对应数据的条数。
也支持多重聚合,先按应用id聚合,再按应用name聚合;聚类结果会嵌套两个buckets
lambdaEsQueryWrapper wrapper = new lambdaEsQueryWrapper();
wrapper.groupBy(AttackAlarm::getAppId,AttackAlarm::getAppName);
SearchResponse response = attackAlarmMapper.search(wrapper);