这里先说几个点:
1: TermsAggregationBuilder 聚合,需要分组后的数据,需要到searchResponse.getAggregations.getBuckets() 中去取
2 :
int from = (pageVo.getPage() - 1) * pageVo.getPageSize();
SearchRequest searchRequest = new SearchRequest(ElasticSearchConstant.INDEX_Holding);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("hdIfBorrow", "c"))
.must(QueryBuilders.rangeQuery("hdReturnDate").lt(DateUtils.date2Str(time)))
.must(QueryBuilders.termQuery("libId.keyword", libId))
);
TermsAggregationBuilder aggregation = AggregationBuilders.terms("by_reader").field("readerId")
.size(pageVo.getPage() * pageVo.getPageSize())
.subAggregation(AggregationBuilders.topHits("books")
.fetchSource(new String[]{"readerId", "libName", "hdReturnDate", "boName"}, null)
.size(100).sort("hdReturnDate")
);
CardinalityAggregationBuilder cardinalityAggregation = AggregationBuilders.cardinality("uniqueReader")
.field("readerId");
searchSourceBuilder.aggregation(aggregation);
searchSourceBuilder.aggregation(cardinalityAggregation);
searchSourceBuilder.size(0);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
return ResultResponse.fail("ES查询失败!");
}
Cardinality cardinality = searchResponse.getAggregations().get("uniqueReader");
long totalCount = cardinality.getValue();
Map<String, UrgeReturnDTO> map = new HashMap<>();
Terms readers = searchResponse.getAggregations().get("by_reader");
for (int n = from - 1; n < readers.getBuckets().size(); n++) {
Terms.Bucket readerBucket = readers.getBuckets().get(n);
String readerId = readerBucket.getKeyAsString();
UrgeReturnDTO urgeReturnDTO = new UrgeReturnDTO();
map.put(readerId, urgeReturnDTO);
TopHits topHits = readerBucket.getAggregations().get("books");
urgeReturnDTO.setCount(topHits.getHits().getHits().length);
urgeReturnDTO.setLibId(libId);
urgeReturnDTO.setReaderId(readerId);
for (SearchHit hit : topHits.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String libName = String.valueOf(sourceAsMap.get("libName"));
urgeReturnDTO.setLibraryName(libName);
// 保存书名
if (sourceAsMap.containsKey("boName")) {
String boName = String.valueOf(sourceAsMap.get("boName"));
if (ObjectUtil.isEmpty(urgeReturnDTO.getBookNames())) urgeReturnDTO.setBookNames(boName);
else urgeReturnDTO.setBookNames(urgeReturnDTO.getBookNames() + "," + boName);
}
String hdReturnDate = String.valueOf(sourceAsMap.get("hdReturnDate"));
// 计算最长的逾期时间
int i = 0;
try {
i = DateUtils.daysBetween(hdReturnDate, DateUtils.getDate());
} catch (ParseException e) {
e.printStackTrace();
return ResultResponse.fail("天数计算失败!存在错误数据!");
}
if (ObjectUtil.isEmpty(urgeReturnDTO.getDays()) || urgeReturnDTO.getDays() < i)
urgeReturnDTO.setDays(i);
}
}