title: ElasticSearch date range query aggregation using Java API
body: <p>Hi I have the document for cpu usage with date_time field inside it. Now I would like to find avg cpu usage for the date range. I have come up with the following solution. Please let me know if there are any advance or better approach as I am new to Elastic Search.</p>
  
  <pre><code>client.prepareSearch("myindex").
         setTypes("mytype").
         setQuery(
             QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
             FilterBuilders.andFilter(FilterBuilders.termFilter("server","x"),
             FilterBuilders.rangeFilter(date_time).from(fdate).to(tdate)))).get()
  </code></pre>
  
  <p>Now above query returns me as expected documents which falls within from/to date range. Now what I try to do is I find all unique dates from these documents using <code>SearchHits</code>and I store this unique combinations of dates in a <code>HashSet</code> and now for all items inside this <code>HashSet</code> I execute the following query</p>
  
  <pre><code>client.prepareSearch("myindex").
         setTypes("mytype").
         setQuery(
             QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
             FilterBuilders.andFilter(FilterBuilders.termFilter("server","x"),
             FilterBuilders.termFilter(date_time),"dateinputfromloop"))).
         addAggregation(AggregationBuilders.avg("cpu_agg").field("cpu_time"))
         .get()
  </code></pre>
  
  <p>Now above query works fine and gives output I get avg CPU for each date time combination. I was wondering if these is any better approach as I execute above query in a loop for all date combinations. Please guide thanks in advance.</p>