Search code examples
elasticsearchelasticsearch-5

How can we get the minimum and maximum dates of data in each indices in elastic search?


How can we get the minimum and maximum dates of data in each indices in elastic search?

I was going through the documentation but not able to understand which API will help get the min and max dates of data in each indices in elastic search.


Solution

  • Tldr;

    I believe you could address that using the aggregation feature of Elasticsearch. You could use the Min and Max metric aggregation.

    Solution

    This would look like that using the api:

    GET <The Index>/_search
    {
      "size": 0, 
      "query": {
        "match_all": {}
      },
      "aggs": {
        "min": {
          "min": {
            "field": "<The date>"
          }
        },
        "max":{
          "max": {
            "field": "<The date>"
          }
        }
      }
    }
    

    The result should look like so:

    {
      "took": 0,
      "timed_out": false,
      "_shards": {
    ...
      },
      "hits": {
        "total": {
          "value": 10000,
          "relation": "gte"
        },
        "max_score": null,
        "hits": []
      },
      "aggregations": {
        "min": {
          "value": 1660521603764,
          "value_as_string": "2022-08-15T00:00:03.764Z"
        },
        "max": {
          "value": 1665431791459,
          "value_as_string": "2022-10-10T19:56:31.459Z"
        }
      }
    }