How can I construct a filter that matches a bucket from a date_histogram aggregation?

Say for example I have a date_histogram aggregation that looks like this:

{
        "date_histogram": {
            "field": "request_datetime",
            "interval": "hour"
        }
}

I get back buckets that look like this:

[
    {
        "key_as_string": "2017-09-25T07:00:00.000Z",
        "key": 1506322800000,
        "doc_count": 20
    },
    {
        "key_as_string": "2017-09-25T08:00:00.000Z",
        "key": 1506326400000,
        "doc_count": 27
    },
    {
        "key_as_string": "2017-09-25T09:00:00.000Z",
        "key": 1506330000000,
        "doc_count": 22
    },
    {
        "key_as_string": "2017-09-25T10:00:00.000Z",
        "key": 1506333600000,
        "doc_count": 42
    },
]

I'm providing a UI where users can select one of those histogram buckets to further filter the results. When they select a bucket, what is the correct way of constructing a filter that will apply to those results?

For year I went with this... but I don't know if this is guaranteed to return the exact same count of results as the corresponding date_histogram bucket:

{
    "range": {
        "request_datetime": {
            "gte": "2017-10-09T00:00:00Z",
            "lte": "2017-10-09T23:59:59Z"
        }
    }
}

What should this look like for day/hour/etc?

Got a great answer to this from Honza: https://github.com/elastic/elasticsearch-dsl-py/blob/master/elasticsearch_dsl/faceted_search.py#L152-L158

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