title: Daterange + top_hits aggregation (as subaggregation) with Elasticsearch Java API Client 7.17.x
body: <p>I've been at this for a day and I don't quite understand how I do it! This is the query I want to &quot;recreate&quot; with the new Java API Client (using Spring Boot)</p>
  <pre class="lang-json prettyprint-override"><code>{
    &quot;aggs&quot;: {
      &quot;range&quot;: {
        &quot;date_range&quot;: {
          &quot;field&quot;: &quot;timestamp&quot;,
          &quot;ranges&quot;: [
            { &quot;to&quot;: &quot;now-2d&quot; } 
          ]
        }
      }
    ,
    &quot;aggs&quot;: {
        &quot;top_hits&quot;: {
          &quot;_source&quot;: {
                &quot;includes&quot;: [ &quot;Id&quot;, &quot;timestamp&quot; ]
              }
        }
    }
  }
  }
  </code></pre>
  <p>I tried doing it with <code>DateRangeAggregation.of</code> but I can't seem to get the right results or type. Here's what I have</p>
  <pre class="lang-java prettyprint-override"><code>SearchResponse&lt;MyDto&gt; response = client.search(b -&gt; b
                  .index(&quot;test-index&quot;)
                  .size(0) 
                  .aggregations(&quot;range&quot;,a-&gt;a.dateRange(DateRangeAggregation.of(d-&gt;d
                    .field(&quot;timestamp&quot;).ranges(r-&gt;r.to(t-&gt;t.expr(&quot;now-2d&quot;)))))),
                      .aggregations(&quot;hits&quot;, a -&gt; a
                          .topHits(h-&gt;h.source(SourceConfig.of(c-&gt;c.filter(f-&gt;f.includes(Arrays.asList(&quot;Id&quot;, &quot;timestamp&quot;))))))),
                  MyDto.class 
              );
  </code></pre>
  <p>I've also tried removing the <code>subaggregation</code> and query for now, but I don't seem to be on the right track to even get the number of <code>doc_count</code> from the bucket. I kind of don't get how to work with the <code>dateRange()</code> here.</p>
  <p>Edit: I played around a bit and was able to at least get the number of <code>doc_count</code>, I'm not very sure if this is a good way to do it though?</p>
  <pre><code>Aggregation agg = Aggregation.of(a -&gt; a
              .dateRange(d-&gt;d.field(&quot;timestamp&quot;).ranges(r-&gt;r.to(FieldDateMath.of(v-&gt;v.expr(&quot;now-2d&quot;))))));
          
  SearchResponse&lt;MyDto&gt; response = client.search(b -&gt; b
                 .index(&quot;test-index&quot;)
                 .size(0) 
                 .aggregations(&quot;range&quot;, agg),
                  MyDto.class 
              );
  
  return response.aggregations().get(&quot;range&quot;).dateRange().buckets().array().get(0).docCount();
  </code></pre>
  <p>I also fixed the query above, it had an unnecessary extra query that broke the result.</p>