# Date Range Search based on Oldest Document

**URL:** https://discuss.elastic.co/t/date-range-search-based-on-oldest-document/346255
**Category:** Elasticsearch
**Created:** [November 2, 2023, 2:29am UTC](https://discuss.elastic.co/t/date-range-search-based-on-oldest-document/346255 "2023-11-02T02:29:19Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![samjsem](https://avatars.discourse-cdn.com/v4/letter/s/b5ac83/32.png) [@samjsem](https://discuss.elastic.co/u/samjsem)
#### Post date: [November 2, 2023, 2:29am UTC](https://discuss.elastic.co/t/date-range-search-based-on-oldest-document/346255/1 "2023-11-02T02:29:19Z")

</div>

Hi team,

I am writing to ask: What is the best way to construct a query to satisfy the following requirement: Date range specification in the `filter` clause of a `boolean` query so that `gte` is based on the oldest document in the index.

Consider:

```auto
...
"filter":
{
  "range":
  {
    "CustomElasticSearchDateTime":
    {
      "gte": "OLDEST DOCUMENT", <-- (How to get the oldest document here based on the index being searched?)
      "lte": "OLDEST DOCUMENT + 6M/M",
      "relation": "WITHIN"
     }
  }
}
...

```

Here is how I am currently get the oldest document from the index:

```auto
{
	"size": 1,
	"_source": false,
	"sort":
	{
		"CustomElasticSearchDateTime": "asc"
	},
	"query":
	{
		"match_all": {}
	}
}

```

But it does not seem possible to add this query under the `gte` of the previous query; or, is it possible. Any help here would be much appreciated.

Thank you

---

<div class="post-metadata">

### Author: ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)
#### Post date: [November 2, 2023, 3:03am UTC](https://discuss.elastic.co/t/date-range-search-based-on-oldest-document/346255/2 "2023-11-02T03:03:48Z")

</div>

You need to run 2 queries.  
One to get that value and the second one using the value.

I don't think you can do this with one single query yet.

It might be possible in the future with ES|QL.

---

<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: [November 30, 2023, 3:04am UTC](https://discuss.elastic.co/t/date-range-search-based-on-oldest-document/346255/3 "2023-11-30T03:04:08Z")

</div>

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