'How to elastic search in python for the last 24 hours?

I want to retrieve elastic search data into python. I am using the following code:

    es = Elasticsearch(['https://es-host/'],
                       http_auth=(username, password))

    # get last 24h pm25 data
    query = {
        "range": {"TimeStamp": {"gte": "now-8d/d", "lte": "now/d", "format": "epoch_millis"}}
    }
    result = es.search(index="test-dev", q="pm25", body=
    {
        "query": query
    }
                       )

However the data I get is not from the last 24 hours. The timestamps contain data from 1611506930000, which is 24 january 2021. How could I fix the query to get only the last 24 hour data for the pm2.5 values?



Solution 1:[1]

Here you are trying to get the data for the last 8 days (with now-8d/d). It is weird though that you are retrieving data from january. Furthermore, your query format is wrong. You want to filter your results using your range, which translates in elastic search queries by:

query =  {
    "bool": {
       "must": [
         {
            "range": {
               "Timestamp": {
                  "gte": "now-24h",
                  "lt": "now"
                }
           }        
        }
     ]
   }

}

Also, verify that your field timestamp has the correct name.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1