Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 514
Umesh K Avatar asked Jul 25 '14 20:07

Umesh K


2 Answers

I think this will help.

SearchResponse response=
                client.prepareSearch("your_index_name_here").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.

like image 117
progrrammer Avatar answered Oct 01 '22 11:10

progrrammer


since elastic search 2.3, FilterBuilders class has been removed from JavaAPI. you can use

QueryBuilder qb = QueryBuilders.boolQuery()
        .must(QueryBuilders.matchQuery("_all", "JPMORGAN"))
        .must(QueryBuilders.matchQuery(field, value)) ;

instead, and set it to

.setQuery(qb).
like image 28
Sean Zhu Avatar answered Oct 01 '22 13:10

Sean Zhu