private BoolQueryBuilder getQueryBuilder(QueryCollectWaterDataPageRequestVO requestVO) {BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();if (!CollectionUtils.isEmpty(requestVO.getCompanyIds())) {//termsQuery 精确查找corpId字段为精确的多个值,和mysql的in类似queryBuilder.must(QueryBuilders.termsQuery("corpId", requestVO.getCompanyIds()));}if (requestVO.getWaterMeterNumber() != null) {//matchPhraseQuery 模糊查询waterMeterNumber中包含某一个值,如果值为字符串最好用这个queryBuilder.must(QueryBuilders.matchPhraseQuery("waterMeterNumber", "*" + requestVO.getWaterMeterNumber() + "*"));}//rangeQuery 范围查询collectTime 大于等于和小于等于某个值if (requestVO.getStartCollectTime() != null) {queryBuilder.must(QueryBuilders.rangeQuery("collectTime").gte(requestVO.getStartCollectTime().getTime()).lte(requestVO.getEndCollectTime().getTime()));}return queryBuilder;}
BoolQueryBuilder queryBuilder = getQueryBuilder(requestVO);NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()//条件过滤.withQuery(queryBuilder)//分页.withPageable(PageRequest.of(requestVO.getPageNum(), requestVO.getPageSize())).withSort(SortBuilders.fieldSort("collectTime").order(SortOrder.DESC))//设置查询时返回的总数是否超过es设置的限制,true是解除限制默认为false.withTrackTotalHits(true).build();SearchHits<ESCollectWaterDataPageResultVO> searchHit = elasticsearchRestTemplate.search(searchQuery, ESCollectWaterDataPageResultVO.class);List<QueryCollectWaterDataPageResultVO> resultList = new ArrayList<>();if (searchHit.getTotalHits() > 0) {searchHit.forEach(content -> {QueryCollectWaterDataPageResultVO resultVO = new QueryCollectWaterDataPageResultVO();BeanUtils.copyProperties(content.getContent(), resultVO);resultVO.setCuWaterData(content.getContent().getData());resultVO.setOneWaterData(content.getContent().getOneData());resultVO.setTwoWaterData(content.getContent().getTwoData());resultVO.setThreeWaterData(content.getContent().getThreeData());resultVO.setCurrentCollectTime(content.getContent().getCollectTime());resultList.add(resultVO);});}BasePageResultDto<QueryCollectWaterDataPageResultVO> pageResultVOBasePageResultDto = new BasePageResultDto((int)searchHit.getTotalHits(), resultList);