elasticsearchTemplate的聚合查詢

直接上代碼:java

// 建立一個查詢條件對象
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 拼接查詢條件
queryBuilder.should(QueryBuilders.termQuery("字段", "值"));
// 建立聚合查詢條件
TermsAggregationBuilder agg = AggregationBuilders.terms("聚合名稱,自定義,取出時會用到").field("聚合字段").size(100);// size是查詢聚合出來的條數
// 建立查詢對象
SearchQuery build = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder) //添加查詢條件
                .addAggregation(agg) // 添加聚合條件
                .withPageable(PageRequest.of(0, 1)) //符合查詢條件的文檔分頁(不是聚合的分頁)
                .build();

// 執行查詢
AggregatedPage<TestEntity> testEntities = elasticsearchTemplate.queryForPage(build, TestEntity.class);

// 取出聚合結果
Aggregations entitiesAggregations = propertyInfoEntities.getAggregations();
        Terms terms = (Terms)propertyInfoEntities.getAggregation("聚合名稱,以前自定義的");

// 遍歷取出聚合字段列的值,與對應的數量
for (Terms.Bucket bucket : terms.getBuckets()) {
            String keyAsString = bucket.getKeyAsString(); // 聚合字段列的值
            long docCount = bucket.getDocCount();// 聚合字段對應的數量
        }

多字段聚合:數據結構

// 建立一個查詢條件對象
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 拼接查詢條件
queryBuilder.should(QueryBuilders.termQuery("字段", "值"));
// 建立聚合查詢條件

TermsAggregationBuilder agg1 = AggregationBuilders.terms("聚合名稱2").field(聚合字段2).size(100)

TermsAggregationBuilder agg = AggregationBuilders.terms("聚合名稱1").field("聚合字段1").size(100).subAggregation(agg1)//拼接上上一個聚合條件
// 建立查詢對象
SearchQuery build = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder) //添加查詢條件
                .addAggregation(agg) // 添加聚合條件
                .withPageable(PageRequest.of(0, 1)) //符合查詢條件的文檔分頁(不是聚合的分頁)
                .build();

// 執行查詢
AggregatedPage<TestEntity> testEntities = elasticsearchTemplate.queryForPage(build, TestEntity.class);

// 取出聚合結果
Aggregations entitiesAggregations = propertyInfoEntities.getAggregations();
        Terms terms = (Terms)propertyInfoEntities.getAggregation("聚合名稱");

// 遍歷最外層的聚合結果
for (Terms.Bucket bucket : terms.getBuckets()) {
            String keyAsString = bucket.getKeyAsString(); // 聚合字段列的名稱
            long docCount = bucket.getDocCount();// 聚合字段對應的數量
	    // 獲取內部的聚合字段信息
            Aggregations aggregations = bucket.getAggregations();
            Terms terms2 = aggregations.get("聚合名稱2");
	// 遍歷獲取agg1的聚合信息
	for (Terms.Bucket bucket1 : terms2.getBuckets()) {
                String keyAsString2 = bucket.getKeyAsString(); // 聚合字段列的名稱
                long docCount2 = bucket.getDocCount();// 聚合字段對應的數量
            }
        }

更多字段聚合按照以上類推,若是實在對於結構不理解能夠將查詢語句打印出來,將打印語句拿到Kibana之類的查詢工具中查詢看下結構,或者直接Debug看下數據結構,就比較好理解了elasticsearch

相關文章
相關標籤/搜索