How to use elasticsearch java api to apply aggregations on a query result

nobodyg
Fri, 06 Jun 2025 20:00:31 +0000
Elasticsearch

I am using co.elastic.clients:elasticsearch-java:9.0.1

I am trying to apply a query and then apply aggregations
the query is about to get the user name and visiting dates within a date range

the result could be:
userA 2025-06-01
userA 2025-06-01
userA 2025-06-02
userA 2025-06-02
userB 2025-06-01
userB 2025-06-02
userB 2025-06-02
userB 2025-06-03

the aggregations is about to get the number of visiting days for each user
the result in this case is:
userA: 2
userB: 3

I tried apply a query then apply termAggregations, also tried apply a filterAggregation then apply termAggregations, both not work

not sure how to achieve this?

select username, count(visitdate)
select distinct username, visitdate
from ...
where visitdate between ... and...
group by username

code samples are appreciated

thank you in advance

5 posts - 3 participants