# Aggregation with java High Level Rest Client

**URL:** <https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447>\
**Category:** Elasticsearch\
**Created:** [March 6, 2020, 11:40am UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447 "2020-03-06T11:40:29Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jonixo](https://avatars.discourse-cdn.com/v4/letter/j/e19adc/32.png) [@Jonixo](https://discuss.elastic.co/u/Jonixo)\
**Post date:** [March 6, 2020, 11:40am UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447/1 "2020-03-06T11:40:29Z")

</div>

I manage to create a working query but I'm having hard time converting it to java.

Working query: `GET edgedevicedata/_search { "size": 0, "aggs": { "by_days": { "date_histogram": { "field": "@timestamp", "fixed_interval": "3d" }, "aggs": { "totalValue": { "sum": { "field": "value" } },"minValue": { "min": { "field": "value" } },"maxValue": { "max": { "field": "value" } },"avgValue": { "avg": { "field": "value" } } } } } }`

My java code; `RestHighLevelClient client = new RestHighLevelClient(builder);

```
    //range query for start and end date
    QueryBuilder rangeQuery = QueryBuilders
            .rangeQuery("time")
            .from("0")
            .to("999999999999999999")
            .includeLower(false)
            .includeUpper(false);

    //term query for sensorId (sensor type)
    QueryBuilder termsQuery = QueryBuilders.boolQuery()
            .must(QueryBuilders.termsQuery("sensorId","1"));

    //term query for deviceId
    QueryBuilder termsQuery2 = QueryBuilders.boolQuery()
            .must(QueryBuilders.termsQuery("deviceId","device1"));

    //combining 3 querries
    QueryBuilder qb = QueryBuilders
            .boolQuery()
            .must(rangeQuery)
            .must(termsQuery)
            .must(termsQuery2);

    //creating search request
    SearchRequest searchRequest = new SearchRequest();
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(qb);
    searchSourceBuilder.from(0);
    searchSourceBuilder.size(1000);

    DateHistogramAggregationBuilder dateAggregation=
            AggregationBuilders.dateHistogram("date_aggregation")
                    .field("timestamp")
                    .fixedInterval(DateHistogramInterval.days(1))
            .subAggregation(AggregationBuilders.max("maxValue")
                .field("value"))
            .subAggregation(AggregationBuilders.min("minValue")
                    .field("value"))
            .subAggregation(AggregationBuilders.avg("avgValue")
                    .field("value"))
            .subAggregation(AggregationBuilders.sum("totalValue")
                    .field("value"));

    searchSourceBuilder.aggregation(dateAggregation);
    searchRequest.source(searchSourceBuilder);

    //setting up for response
    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

    //getting gits
    SearchHits hits = searchResponse.getHits();`

```

Expected output example: ` "aggregations" : { "by_minute" : { "buckets" : [ { "key_as_string" : "2019-12-28T00:00:00.000Z", "key" : 1577491200000, "doc_count" : 6, "totalValue" : { "value" : 125.0 }, "avgValue" : { "value" : 20.833333333333332 }, "minValue" : { "value" : 15.0 }, "maxValue" : { "value" : 29.0 } }`

Output im getting: `{ "_index" : "edgedevicedata", "_type" : "_doc", "_id" : "rDryZ28BtB64rZAMaqqO", "_score" : 3.0, "_source" : { "sensorId" : 1, "deviceId" : "device1", "time" : 1577996937761, "value" : 29.0, "@version" : "1", "@timestamp" : "2020-01-02T20:28:57.766Z" } }`

I'm sorry about the format of queries but I don't know how to make them look good.

---

<div class="post-metadata">

**Author:** ![Jonixo](https://avatars.discourse-cdn.com/v4/letter/j/e19adc/32.png) [@Jonixo](https://discuss.elastic.co/u/Jonixo)\
**Post date:** [March 6, 2020, 1:00pm UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447/2 "2020-03-06T13:00:15Z")

</div>

I decided to ditch high level client and used low level client.

It works even though it looks awful.

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [March 6, 2020, 3:59pm UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447/3 "2020-03-06T15:59:56Z")

</div>

Welcome!

Here is how I'm writing that kind of thing in another project.  
Hope this could help.

> <https://github.com/dadoonet/legacy-search/blob/3767592dac4d30d6fe28a8048579c367b0e5c4ec/src/main/java/fr/pilato/demo/legacysearch/dao/ElasticsearchDao.java#L101-L124>

---

<div class="post-metadata">

**Author:** ![Jonixo](https://avatars.discourse-cdn.com/v4/letter/j/e19adc/32.png) [@Jonixo](https://discuss.elastic.co/u/Jonixo)\
**Post date:** [March 6, 2020, 6:07pm UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447/4 "2020-03-06T18:07:22Z")

</div>

Thank you very much,

I just realized after reading your code that I'm actually printing hits, not aggregations. There wasn't any problem with my code 🙂

I'm glad I found it before someone else so I can be less embarrassed.

To print the aggregations above you can use this Its raw but usable:

```
        Histogram agg = searchResponse.getAggregations().get("date_aggregation");

    // For each entry
    for (Histogram.Bucket entry : agg.getBuckets()) {
        Min min_agg = entry.getAggregations().get("minValue");
        Max max_agg = entry.getAggregations().get("maxValue");
        Avg avg_agg = entry.getAggregations().get("avgValue");
        Sum sum_agg = entry.getAggregations().get("totalValue");
        System.out.println("minValue: " +min_agg.getValue()+" maxValue: " +max_agg.getValue()+" avgValue: " +avg_agg.getValue()+" totalValue: " +sum_agg.getValue());
    }
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [April 3, 2020, 6:07pm UTC](https://discuss.elastic.co/t/aggregation-with-java-high-level-rest-client/222447/5 "2020-04-03T18:07:29Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
