es数据聚合(包含java代码实现)

注:聚合的字段不可分词

聚合的分类

es数据聚合(包含java代码实现)_第1张图片

dsl聚合 

使用dsl实现bucker聚合

es数据聚合(包含java代码实现)_第2张图片

#聚合功能
GET /hotel/_search
{
  "size": 0,
  "aggs": {
    "brandAgg": {
      "terms": {
        "field": "brand",
        "size": 20
      }
    }
  }
}
#实现控制排序
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
      }
    }
  }
}

dsl实现metrics聚合

es数据聚合(包含java代码实现)_第3张图片

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

java实现聚合(rest client使用)

es数据聚合(包含java代码实现)_第4张图片

 结果解析

es数据聚合(包含java代码实现)_第5张图片

//聚合
    @Test
    void testAggregation() throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备dsl
        //2.1设置size
        request.source().size(0);
        //2.2聚合
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(10));
        //3.发送请求
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        //4.解析结果
        Aggregations aggregations = search.getAggregations();
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get("brandAgg");
        //获取buckets
        List buckets = brandTerms.getBuckets();
        //遍历
        for (Terms.Bucket bucket : buckets) {
            //获取key
            String keyAsString = bucket.getKeyAsString();
            //获取数值
            long docCount = bucket.getDocCount();
            System.out.println(keyAsString+":"+docCount);
        }
    }

你可能感兴趣的:(es,java,服务器,servlet)