elasticsearch6.6热词统计

public List<String> searchHotWord() {
        try {
            SearchRequest searchRequest = new SearchRequest(indexName);//indexName是索引名称
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            searchRequest.source(searchSourceBuilder);
            //聚合分析查询出现次数最多的10个词汇,hotWord是聚合名称,name是es的字段名
            TermsAggregationBuilder keyword_agg = AggregationBuilders.terms("hotWord").field("name").size(10).order(BucketOrder.count(false));
            searchSourceBuilder.aggregation(keyword_agg);
            searchRequest.source(searchSourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();

            Terms term = aggregations.get("hotWord");
            List<Terms.Bucket> buckets = (List<Terms.Bucket>) term.getBuckets();
            List<String> hotWords = new ArrayList<>();
            for (Terms.Bucket bucket : buckets) {
                String key = (String) bucket.getKey();
                long docCount = bucket.getDocCount();
                hotWords.add(key);
                logger.info("热词:"+key+"数量为:"+docCount);
            }
            return hotWords;
        }catch (Exception e){
            logger.error("热词搜索失败");
        }
        return null;
    }

你可能感兴趣的:(elasticsearch,热词,elasticsearch聚合)