public PageUtils globalSearch(Map<String, Object> params) throws IOException {
MapGet mapGet = MapGet.init(params);
String[] indexName = {"test"};
try{
//创建搜索请求
SearchRequest searchRequest = new SearchRequest(indexName);
//创建构造器,构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryStringQueryBuilder stringQuery = QueryBuilders.queryStringQuery((String) params.get("keyWord")).defaultOperator(Operator.AND);
sourceBuilder.query(stringQuery);
//得分排序
//sourceBuilder.sort("_score", SortOrder.DESC);
sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
sourceBuilder.from();
searchRequest.source(sourceBuilder);
//最大返回结果数量
sourceBuilder.size(10000);
SearchResponse search = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
SearchHit[] hits1 = hits.getHits();
ArrayList<Object> obj = new ArrayList<>();
for (SearchHit documentFields : hits1) {
//获取到hits中的每一个asString
String asString = documentFields.getSourceAsString();
//数据封装
JSONObject jsonObject = JSONObject.parseObject(asString);
obj.add(jsonObject);
}
//分页
int currPage = mapGet.getInt("page"); // 当前页
int pageSize = mapGet.getInt("limit"); // 每页展示多少条数据
if (currPage == 0) {
currPage = 1;
}
int totalCount = obj.size(); // 一共多少条记录
if(obj.size() != 0){
int totalPage = totalCount % pageSize; // 一共多少页
if (totalPage > 0) {
totalPage = totalCount / pageSize + 1;
} else {
totalPage = totalCount / pageSize;
}
int fromIndex = 0; // 开始索引
int toIndex = 0; // 结束索引
if(currPage != totalPage){
fromIndex = (pageSize * (currPage - 1));
toIndex = fromIndex + pageSize;
}else {
fromIndex = (pageSize * (currPage - 1));
toIndex = totalCount;
}
//当前页不存在数据就返回空列表
ArrayList<Object> list = new ArrayList<>();
if(toIndex >obj.size()){
return new PageUtils(list, totalCount, pageSize, currPage);
}
return new PageUtils(obj.subList(fromIndex, toIndex), totalCount, pageSize, currPage);
}
return new PageUtils(obj, totalCount, pageSize, currPage);
}catch (Exception e){
e.printStackTrace();
throw new RRException(e.getMessage());
}
分页 es全局搜索并且分页
最新推荐文章于 2024-05-14 15:11:31 发布