es---elasticsearch7.1.1 QueryBuilders简单查询

代码如下:以分页查询为例

		// 所需要的jar包
		import org.elasticsearch.action.bulk.BulkRequestBuilder;
		import org.elasticsearch.action.delete.DeleteResponse;
		import org.elasticsearch.action.index.IndexRequest;
		import org.elasticsearch.action.index.IndexResponse;
		import org.elasticsearch.action.search.SearchRequest;
		import org.elasticsearch.action.search.SearchResponse;
		import org.elasticsearch.action.support.master.AcknowledgedResponse;
		import org.elasticsearch.client.IndicesAdminClient;
		import org.elasticsearch.client.RequestOptions;
		import org.elasticsearch.client.RestHighLevelClient;
		import org.elasticsearch.cluster.ClusterState;
		import org.elasticsearch.cluster.metadata.IndexMetaData;
		import org.elasticsearch.cluster.metadata.MappingMetaData;
		import org.elasticsearch.common.settings.Settings;
		import org.elasticsearch.common.xcontent.XContentType;
		import org.elasticsearch.search.SearchHit;
		import org.elasticsearch.search.SearchHits;
		import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
		
		public List> getReportRecordCommentList(String doctitle,String createtime_begin,String createtime_end, 			   HttpServletRequest request) {
			int rows1=Integer.parseInt(request.getParameter("rows"));//行数
			int page1=Integer.parseInt(request.getParameter("page"));//当前页数
			SearchRequest req=new SearchRequest(); 
			req.indices("******"); //表名
			SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
			BoolQueryBuilder boolQueryBuilder=	QueryBuilders.boolQuery();
			// 模糊查询
			if(StringUtils.isNotEmpty(doctitle)) {
				boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("doctitle",("*"+doctitle+"*")));
			}
			// 时间段查询 start
			if(!StringUtil.isEmpty(createtime_begin)) {
				boolQueryBuilder.must(QueryBuilders.rangeQuery("createtime.keyword").gt(createtime_begin).includeLower(true));
			}
			if(!StringUtil.isEmpty(createtime_end)) {
				boolQueryBuilder.must(QueryBuilders.rangeQuery("createtime.keyword").lt(createtime_end).includeUpper(true));
			}
			// 时间段查询 end
			
			/**
			 * 一次匹配多个值 这块有一个问题 就是值如果没有定义直接来使用的话是不行的  是查询不到数据的,必须得先定义再使用
			 * 例如:boolQueryBuilder.must(QueryBuilders.termsQuery("recordstatus", "10","20")); 错误写法
			 */
			String s1 = "10";
			String s2 = "20";
			boolQueryBuilder.must(QueryBuilders.termsQuery("recordstatus", s1,s2));
			// 多个匹配也可以传一个数组,这样得话就不需要像上边得写法一样去定义一个变量了
			ArrayList  list = new ArrayList();
			list.add("10");
			list.add("20");
			boolQueryBuilder.must(QueryBuilders.termsQuery("recordstatus", s1,s2));
			// 单个匹配
			String pictureBrowse = "10";
			boolQueryBuilder.must(QueryBuilders.matchQuery("appchnlcode", pictureBrowse));
			sourceBuilder.query(boolQueryBuilder);
			/**
			 * 跟踪总点击量
			 * 该  trackTotalHits参数允许您控制应如何跟踪总命中数
			 * 设置为true搜索响应时,将始终准确跟踪与查询匹配的匹配数 反之返回命中数的下限10000
			 * 如果您不需要很准确的跟踪命中数 那么此处可设置为false,以便于加速搜索
			 */
			sourceBuilder.trackTotalHits(true);
			//设置排序 根据时间排序 值可为DESC/ASC
			sourceBuilder.sort("createtime.keyword",SortOrder.DESC);
			// 分页 start
			sourceBuilder.from((page1-1)*rows1);
			sourceBuilder.size(rows1);
			// 分页 end
			req.source(sourceBuilder);
			// 单表查询数据
			List> list = this.searchlist(req,RequestOptions.DEFAULT);
		}

		public Integer getReportRecordCommentListCount(String doctitle,String createtime_begin,String createtime_end, 			  
		 HttpServletRequest request) {
			SearchRequest req=new SearchRequest(); 
			req.indices("******"); //表名
			SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
			BoolQueryBuilder boolQueryBuilder=	QueryBuilders.boolQuery();
			// 模糊查询
			if(StringUtils.isNotEmpty(doctitle)) {
				boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("doctitle",("*"+doctitle+"*")));
			}
			// 时间段查询 start
			if(!StringUtil.isEmpty(createtime_begin)) {
				boolQueryBuilder.must(QueryBuilders.rangeQuery("createtime.keyword").gt(createtime_begin).includeLower(true));
			}
			if(!StringUtil.isEmpty(createtime_end)) {
				boolQueryBuilder.must(QueryBuilders.rangeQuery("createtime.keyword").lt(createtime_end).includeUpper(true));
			}
			// 时间段查询 end
			/**
			 * 一次匹配多个值 这块有一个问题 就是值如果没有定义直接来使用的话是不行的  是查询不到数据的,必须得先定义再使用
			 * 例如:boolQueryBuilder.must(QueryBuilders.termsQuery("recordstatus", "10","20")); 错误写法
			 */
			String s1 = "10";
			String s2 = "20";
			boolQueryBuilder.must(QueryBuilders.termsQuery("recordstatus", s1,s2));
			// 单个匹配
			String pictureBrowse = "10";
			boolQueryBuilder.must(QueryBuilders.matchQuery("appchnlcode", pictureBrowse));
			sourceBuilder.query(boolQueryBuilder);
			/**
			 * 跟踪总点击量
			 * 该  trackTotalHits参数允许您控制应如何跟踪总命中数
			 * 设置为true搜索响应时,将始终准确跟踪与查询匹配的匹配数 反之返回命中数的下限10000
			 * 如果您不需要很准确的跟踪命中数 那么此处可设置为false,以便于加速搜索
			 */
			sourceBuilder.trackTotalHits(true);
			//设置排序 根据时间排序 值可为DESC/ASC
			sourceBuilder.sort("createtime.keyword",SortOrder.DESC);
			req.source(sourceBuilder);
			// 查询总条数
			int searchlistSize = this.searchlistSize(req,RequestOptions.DEFAULT);
		}
		// 查询执行 数据
		public List> searchlist(SearchRequest request,RequestOptions options) {
		// TODO Auto-generated method stub
		try {
       	 
            SearchResponse response = (SearchResponse) client.search(request,options);
            if (response.getHits() == null) {
                return null;
            }
            List> list = new ArrayList>();
    		SearchHits hits = response.getHits();
    		SearchHit [] searchHits = hits.getHits();
    		TotalHits totalHits = hits.getTotalHits();
    		long numHits = totalHits.value;
    		for(SearchHit hit:searchHits){
    			Map highlightFields = hit.getHighlightFields();
    			Map sourceAsMap = hit.getSourceAsMap();
    			if(highlightFields.get("DOCTITLE")!=null) {
    				sourceAsMap.put("DOCTITLE", highlightFields.get("DOCTITLE").getFragments()[0]);
    			}
    			list.add(sourceAsMap);
    		}
            //response.getHits().forEach(item -> list.add(JSON.parseObject(item.getSourceAsString())));
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}
	
	//  返回总条数
	public Integer searchlistSize(SearchRequest request, RequestOptions options) {
		int num = 0;
		try {
            SearchResponse response = (SearchResponse) client.search(request,options);
            if (response.getHits() == null) {
            	num = 0;
            }
    		SearchHits hits = response.getHits();
    		TotalHits totalHits = hits.getTotalHits();
    		num = (int) totalHits.value;
        } catch (Exception e) {
            e.printStackTrace();
        }
		return num;
	}

这种查询方式要注意一个问题,就是如果ES中的数据量大于100000的时候,哪怕你设置了sourceBuilder.trackTotalHits(true);参数,分页的时候还是会有问题 ,10000之后的数据就会没办法显示,解决办法见:elasticsearch— 修改查询最大返回结果数

你可能感兴趣的:(Elasticsearch)