title: ElasticSearch : Get latest version of each document
body: <p>I'm querying ES to get me list of documents within some specific timestamp. Now I encountered a scenario where we had multiple versions of single documentId. By default ES returned me all the versions of that single documentId. My requirement is to get only one last version of all the docs.</p>
  <p>Also I wanted to get all the ES response sorted in Ascending order of one the indexed timestamp field(called as streamingSegmentStartTime)</p>
  <p>my current query looks like following :
   </p>
  <pre><code>{&quot;size&quot;:25,&quot;query&quot;:{&quot;bool&quot;:{&quot;must&quot;:[{&quot;terms&quot;:{&quot;streamingSegmentId&quot;:[&quot;00002933-be25-3b9c-9970-472b41aa53cc&quot;],&quot;boost&quot;:1.0}},{&quot;range&quot;:{&quot;streamingSegmentStartTime&quot;:{&quot;from&quot;:1644480000000,&quot;to&quot;:1647476658447,&quot;include_lower&quot;:true,&quot;include_upper&quot;:false,&quot;boost&quot;:1.0}}}],&quot;adjust_pure_negative&quot;:true,&quot;boost&quot;:1.0}},&quot;_source&quot;:{&quot;includes&quot;:[&quot;errorCount&quot;,&quot;benefitId&quot;,&quot;streamingSegmentStopTime&quot;, &quot;fanoutPublishTimestamp&quot;, &quot;search.version&quot;],&quot;excludes&quot;:[]},&quot;sort&quot;:[{&quot;streamingSegmentStartTime&quot;:{&quot;order&quot;:&quot;asc&quot;}}, {&quot;_timestamp&quot;: {&quot;order&quot;: &quot;desc&quot;}}]}
  </code></pre>