# Java API REST Client: Grouping and Counting Results by Multiple Keys

**URL:** <https://discuss.elastic.co/t/java-api-rest-client-grouping-and-counting-results-by-multiple-keys/352004>\
**Category:** Elasticsearch\
**Tags:** language-clients\
**Created:** [January 29, 2024, 2:47pm UTC](https://discuss.elastic.co/t/java-api-rest-client-grouping-and-counting-results-by-multiple-keys/352004 "2024-01-29T14:47:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![adgam](https://avatars.discourse-cdn.com/v4/letter/a/49beb7/32.png) [@adgam](https://discuss.elastic.co/u/adgam)\
**Post date:** [January 29, 2024, 2:47pm UTC](https://discuss.elastic.co/t/java-api-rest-client-grouping-and-counting-results-by-multiple-keys/352004/1 "2024-01-29T14:47:29Z")

</div>

Hi,  
I'm working with the base field 'labels' and want to create a search query that groups my results by values for each key. The sample structures include keys like 'application' and 'env.' For instance, I want to group by 'env' and count how many results I have for values like 'production' and 'test.' However, in my use case, it's not just one key I use for grouping but up to five.

```auto
 "labels": {"application": "foo-bar", "env": "production"}
 "labels": {"application": "foo-bar", "env": "test"}

```

Thats what I have so far:

```auto
aggregationMap.put("date", Aggregation.of(
              agg -> agg.dateHistogram(dH -> dH
                      .calendarInterval(finalInterval)
                      .field("@timestamp"))
                  .aggregations("source", so -> so.topHits(th -> th.source(
                              s -> s.filter(f -> f.includes(List.of("event.action", "message", "@timestamp", "labels.*"))))
                          .size(1)
                      )

                  )
                  .aggregations("count", count -> count.sum(s -> s.field("countValue")))
          )
      );

```

I'm using the **Java API REST Client** and I tried many diffrent aproaches, but it does not work at all. Is this possible somehow?

---

<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:** [February 26, 2024, 2:48pm UTC](https://discuss.elastic.co/t/java-api-rest-client-grouping-and-counting-results-by-multiple-keys/352004/2 "2024-02-26T14:48:13Z")

</div>

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