简体   繁体   中英

Elasticsearch relative time range query in Python

I have searched and searched but cannot find an answer for this. I am new to using Elasticsearch with Python and trying to do a simple Python query against my Elasticsearch index which will return a count of the results matching a specific set of criteria in the past hour. I'm getting all the results back using the following (sanitized) code:

 hits = es.count(index='myindex-*',q=thing.rstrip() )

Simple enough right? So is there a way to include a relative time range in this query, or do I need to write some Python to figure out the times to insert as a time range?

Thanks in advance for the help!

Yes, everything you need is a time-based key in your index and then query that key with:

{
    "query" : {
        "range" : {
            "<time_based_key>" : {
                "gte" : "now-1h"
            }
        }
    }
}

To define your time-based key:

curl -XPUT localhost:9200/<database>/<index>/_mapping?pretty -d '
{
    "<index>" : {
        "properties": {
            "<time_based_key>" : {
                "type" : "date",
                "index": "not_analyzed"
            }
        }
    }
}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM