user449355 user449355 - 6 months ago 97
Java Question

Elasticsearch aggregation using Java api

Hi I am trying to do query on elastic search by following the sql query and I want to implement same logic using Java API

select dttime, avg(cpu) from table cpustats where server="X" and dttime="Y" group by dttime,cpu


Now I have the following Java code but it does not return expected output

SearchResponse response = client.prepareSearch("cpuindex")
.setTypes("cputype")
.setQuery(QueryBuilders.matchAllQuery())
.addAggregation(AggregationBuilders.terms("cpu_agg")
.field("cpu").size(100))
.execute().actionGet();


Please guide I am new to Elastic search. Thanks in advance.

Answer

I think this will help.

SearchResponse response=
                client.prepareSearch('yourindex').setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
                FilterBuilders.andFilter(
                        FilterBuilders.termFilter("server","x"),
                        FilterBuilders.termFilter("dt_time","x")
                ))).addAggregation(
                AggregationBuilders.terms("dt_timeaggs").field("dt_time").size(100).subAggregation(
                        AggregationBuilders.terms("cpu_aggs").field("cpu").size(100)
                )
        ).setSize(0).get();

please verify.