赞
踩
注意:我的版本是elasticsearch7.6.2、spring-boot-starter-data-elasticsearch-2.5.6
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
ES分页查询接口实现,直接通过索引别名聚合查询
@SneakyThrows @Override public Page<AnalysisHistoryVO> alarmNamePage(PageParams<FindHistoryDTO> findPageParams) { SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(QueryBuilders.termQuery("companyId", SecurityUtils.getCompanyId())); boolQueryBuilder.must(QueryBuilders.termQuery("status",StaticConstant.ZERO)); boolQueryBuilder.must(QueryBuilders.termQuery("alarmStatus",StaticConstant.ZERO)); if (findPageParams.getModel().getAlarmLevel() != null && findPageParams.getModel().getAlarmLevel() != -1){ boolQueryBuilder.must(QueryBuilders.termQuery("alarmLevel",findPageParams.getModel().getAlarmLevel())); } TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("alarmName").field("alarmName").size(1000); TermsAggregationBuilder level = AggregationBuilders.terms("alarmLevel").field("alarmLevel"); // TermsAggregationBuilder field = AggregationBuilders.terms("status").field("status"); // level.subAggregation(field); aggregationBuilder.subAggregation(level); NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).addAggregation(aggregationBuilder).withTrackTotalHits(true).build(); searchRequest.source(sourceBuilder); SearchHits<EsAlarmHistory> search = elasticsearchRestTemplate.search(build, EsAlarmHistory.class, IndexCoordinates.of("alarm_history_search")); Aggregations aggregations = (Aggregations) search.getAggregations(); Map<AnalysisHistoryVO, Long> count = EsUtil.count(aggregations, AnalysisHistoryVO.class); count.forEach(AnalysisHistoryVO::setDocCount); List<AnalysisHistoryVO> historyVOList = new ArrayList<>(count.keySet()); //list按指定长度分割,按500分割 List<List<AnalysisHistoryVO>> splitList = ListUtil.split(historyVOList, (int) findPageParams.getSize()); Page<AnalysisHistoryVO> page = new Page(); if (splitList.size()>0) { page.setRecords(splitList.get((int) findPageParams.getCurrent() - 1)); } page.setPages(findPageParams.getSize()); page.setCurrent(findPageParams.getCurrent()); page.setTotal(historyVOList.size()); return page; }
实体中无需添加ES索引名信息
@Data
public class EsAlarmHistoryVO implements Serializable {
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。