关于elasticsearch聚合查询只有10条数据(java)

业务:查询热点词汇

实现:使用聚合函数,统计前 100 条高频词汇

解决聚合只显示 10 条问题:

1
在构建termsBuilder聚合查询对构建器时,在最后设置size值为100,完美解决

复制代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 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;
    }
Licensed under CC BY-NC-SA 4.0
最后更新于 Jan 06, 2025 05:52 UTC
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计
Caret Up