# Query the last match by a field

**URL:** <https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226>\
**Category:** Elasticsearch\
**Created:** [April 12, 2017, 9:27pm UTC](https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226 "2017-04-12T21:27:35Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mr\_chang7](https://avatars.discourse-cdn.com/v4/letter/m/cc9497/32.png) [@mr\_chang7](https://discuss.elastic.co/u/mr_chang7)\
**Post date:** [April 12, 2017, 9:27pm UTC](https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226/1 "2017-04-12T21:27:35Z")

</div>

Hey guys,

This might be a basic query but cannot figure it out.

Among the documents of a certain time window, I like to find the last one (by time) which matches by given field(s).  
Any ideas?

FYI, I'm using the latest ES.

Thanks!  
Ray

---

<div class="post-metadata">

**Author:** ![eperry](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/eperry/32/551_2.png) [@eperry](https://discuss.elastic.co/u/eperry)\
**Post date:** [April 12, 2017, 10:22pm UTC](https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226/2 "2017-04-12T22:22:53Z")

</div>

You could just sort the data and you would then know the first or last document of all the documents returned is the one you want. You could even set your fetch size to 1 and you would only ever get the document you wanted.

sort of a good example

> <https://stackoverflow.com/questions/36354110/elasticsearch-get-the-last-document-for-a-given-field-if-it-exists>

---

<div class="post-metadata">

**Author:** ![mr\_chang7](https://avatars.discourse-cdn.com/v4/letter/m/cc9497/32.png) [@mr\_chang7](https://discuss.elastic.co/u/mr_chang7)\
**Post date:** [April 12, 2017, 11:19pm UTC](https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226/3 "2017-04-12T23:19:42Z")

</div>

Awesome! That's what exactly I was looking for.

Thanks Ed!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 10, 2017, 11:22pm UTC](https://discuss.elastic.co/t/query-the-last-match-by-a-field/82226/4 "2017-05-10T23:22:05Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
