Get Current Time and date

I need to retrieve all the records between Start of the day to End of the day

For Eg: 2018-01-29 00:00:00 - 2018-01-29 23:59:59

Similarly, I need to get current Time and Date.

GET _search
{
  "size": 1, 
  "script_fields": {
    "now": {
      "script": "new Date().getTime()"
    }
  }
}

But this gives me the result as

{
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 76,
    "successful": 76,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 17257117,
    "max_score": 1,
    "hits": [
      {
        "_index": ".kibana",
        "_type": "doc",
        "_id": "index-pattern:c23523c0-f6b7-11e7-864f-3d5a306a7451",
        "_score": 1,
        "fields": {
          "now": [
            1517230755079
          ]
        }
      }
    ]
  }
}

But the required Format is

{
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 76,
    "successful": 76,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 17257117,
    "max_score": 1,
    "hits": [
      {
        "_index": ".kibana",
        "_type": "doc",
        "_id": "index-pattern:c23523c0-f6b7-11e7-864f-3d5a306a7451",
        "_score": 1,
        "fields": {
          "now": [
            2018-01-29 18:33:42
          ]
        }
      }
    ]
  }
}

If you need to get all records, you should use constant_query it's allot faster than normal query. Because it doesn't add weight so search.

My Example:

GET index/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "range": {
                "date": {
                  "gte": "2018-01-29",
                  "lte": "2018-01-29",
                  "format": "YYYY-dd-MM",
                  "time_zone": "Europe/..."
                }
              }
            }
          ]
        }
      }
    }
  }
}

Script_fields are not for searching, they are for postprocessing search results:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html

Have a look at Date Math. If you wanted to hit records for the current day, you could use

{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now/d",
            "lt": "now+1d/d"
          }
        }
      }
    }
  }
}

or for the previous day

{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now-1d/d",
            "lt": "now/d"
          }
        }
      }
    }
  }
}

To iterate over all records, I'd recommend using the Scroll API.

1 Like

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