dsl实现聚合(包括RestClient实现)

# 聚合功能,自定义排序规则

GET /hotel/_search
{
  "size":0,
  "aggs":{
    "brandAgg":{
      "terms": {
        "field": "brand",
        "size":20,
        "order": {
          "_count": "asc"
        }
      }
    }
  }
}


GET /hotel/_search
{
  "query": {
    "range": {
      "price": {
        "lte": 200
      }
    }
  }, 
  "size":0,
  "aggs":{
    "brandAgg":{
      "terms": {
        "field": "brand",
        "size":20,
        "order": {
          "_count": "asc"
        }
      }
    }
  }
}


#嵌套聚合metric
GET /hotel/_search
{
  "size":0,
  "aggs":{
    "brandAgg":{
      "terms": {
        "field": "brand",
        "size":20,
        "order": {
          "scoreAgg.avg": "desc"
        }
      },
      "aggs": {
        "scoreAgg": {
          "stats": {
            "field": "score"
          }
        }
      }
    }
  }
}


//RestClient实现

 @Test
    void testAggregation() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        request.source().size(0);
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(10)
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Terms brandTerms = aggregations.get("brandAgg");
        List buckets = brandTerms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            System.out.println(key);
        }
    }

你可能感兴趣的:(ES的学习,http,网络,es,spring,cloud,spring,boot)