1

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!

1 Answer 1

2

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"
            }
        }
    }
}'
Sign up to request clarification or add additional context in comments.

3 Comments

OK that's helpful. Two questions: Can I use @timestamp as my time based key, and how does this translate into using count inside Python?
Yes, you can use whatever key you want, you just need to set it with a date (datetime.now() in Python?). Relatively to count, the dictionary returned by elasticsearch will contains a key called hits and inside the value of hits you will have another key called total meaning the number of results returned.
That got me where I needed to be. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.