业务:查询热点词汇
实现:使用聚合函数,统计前100条高频词汇
解决聚合只显示10条问题:
在构建termsBuilder聚合查询对构建器时,在最后设置size值为100,完美解决
public ESReturn searchHotPoint(Integer day, Integer num) { ESReturn esReturn = new ESReturn(); List<BucketsReturnVO> bucketsReturnVOList = new ArrayList<>(); Client client = clientHelper.getClient(); //分组聚合 AggregationBuilder termsBuilder = AggregationBuilders.terms("by_searchKeyword").field("searchKeyword").size(100); AggregationBuilder countBuilder = AggregationBuilders.count("searchKeywordCount").field("searchKeyword"); termsBuilder.subAggregation(countBuilder); SearchRequestBuilder sb = client.prepareSearch("search_history").setTypes("user_search_history"); SearchResponse sr = sb.setQuery(QueryESUtil.getQueryBuildByDay(day)) .addAggregation(termsBuilder) .get(); SearchHits hits = sr.getHits(); SearchHit[] lists = hits.getHits(); logger.info("总命中数:" + hits.totalHits); logger.info("总长度:" + lists.length); Aggregation bySearchKeyword = sr.getAggregations().asMap().get("by_searchKeyword"); //转成BySearchKeywordVO对象 BySearchKeywordVO keywordVO = GsonUtil.GsonToBean(bySearchKeyword.toString(), BySearchKeywordVO.class); List<Buckets> buckets = keywordVO.getBy_searchKeyword().getBuckets(); //整理返回数据 for (Buckets bucket : buckets) { BucketsReturnVO bucketsReturnVO = new BucketsReturnVO(); bucketsReturnVO.setKeyword(bucket.getKey()); bucketsReturnVO.setDocCount(bucket.getDoc_count()); bucketsReturnVOList.add(bucketsReturnVO); } esReturn.setTotal(hits.totalHits); esReturn.setData(bucketsReturnVOList); return esReturn; }