Java 根据条件分页查询 Es数据

 QueryBuilder 简单查询简单查询可以参考我的另一篇博客https://blog.csdn.net/qq_36189144/article/details/88708684

  public ResultData select(List longList,Integer pageIndex,Integer pageSize, String carNum, String devNum,
                                    String startTime, String endTime) throws Exception {
        //创建builder
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.termsQuery("unitId",longList));
        builder.must(QueryBuilders.rangeQuery("time.keyword").from(startTime).to(endTime));
        if(!StringUtils.isBlank(carNum)){
            builder.must(QueryBuilders.wildcardQuery("carNum.keyword", "*" + carNum + "*"));
        }
        if(!StringUtils.isBlank(devNum)){
            builder.must(QueryBuilders.wildcardQuery("devNum.keyword", "*" + devNum + "*"));
        }
            //注意!es的分页api是从第0页开始的
        PageRequest page = new PageRequest(pageIndex, pageSize);
        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //将分页设置到构建中
        nativeSearchQueryBuilder.withPageable(page);
        //将搜索条件设置到构建中
        nativeSearchQueryBuilder.withQuery(builder);
        //设备号升序
        nativeSearchQueryBuilder.withSort(new FieldSortBuilder("devNum").order(SortOrder.ASC));
        //时间降序
        nativeSearchQueryBuilder.withSort(new FieldSortBuilder("time").order(SortOrder.DESC));
        //生产NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();
        //执行
        Page search = nowDataDao.search(query);
        //获取总条数(前端分页需要使用)
        int total = (int) search.getTotalElements();
        //获取查询到的数据内容
        List content = search.getContent();
        //打印总条数
        System.out.println(total);
        List carsHistoryData = getHistoryData(content);
        return ResultData.tableDate(total, carsHistoryData);
//        return content;
    }

 

你可能感兴趣的:(java)