alan
alan

Reputation: 890

Elasticsearch count of documents with values in range

I have a set of documents where each have min and max numerical fields, such as

{ min: 50, max: 100 },
{ min: 75, max: 125 },
{ min: 75, max: 150 },
...

I know beforehand what the highest possible max value can be. What I'd like to do is a bucket aggregation to count the number of documents where the bucket value is contained between (let's say inclusive for the purposes of this example) the document's min and max values. So for example, if I had buckets with keys

60, 80, 100, 120, 140, 160

I would like to get back doc_counts of (respectively):

1, 3, 3, 2, 1, 0

I feel like a range aggregation with a script gets me close but I'm not sure how to get there. Maybe I need a sub aggregation?

Upvotes: 0

Views: 601

Answers (1)

Eugene
Eugene

Reputation: 3957

You need a filters aggregation here where each key corresponds to a separate filter. Here is an example for two keys

{
    "aggs": {
        "ranges": {
            "filters": {
                "filters": {
                    "60": {
                        "bool": {
                            "must": [
                                {
                                    "range": {
                                        "min": {
                                            "gte": 60.0
                                        }
                                    }
                                },
                                {
                                    "range": {
                                        "max": {
                                            "lt": 60.0
                                        }
                                    }
                                }
                            ]
                        }
                    },
                    "80": {
                        "bool": {
                            "must": [
                                {
                                    "range": {
                                        "min": {
                                            "gte": 80.0
                                        }
                                    }
                                },
                                {
                                    "range": {
                                        "max": {
                                            "lt": 80.0
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
}

I don't think there's a simpler way since your ranges are inside your documents in a separate fields

Upvotes: 1

Related Questions