Date Range Aggregation Usage
editDate Range Aggregation Usage
editA range aggregation that is dedicated for date values. The main difference between this aggregation and the normal range aggregation is that the from
and to
values can be expressed in DateMath
expressions, and it is also possible to specify a date format by which the from and
to response fields will be returned.
this aggregation includes the from
value and excludes the to
value for each range.
Be sure to read the Elasticsearch documentation on Date Range Aggregation
Fluent DSL example
edita => a .DateRange("projects_date_ranges", date => date .Field(p => p.StartedOn) .Ranges( r => r.From(DateMath.Anchored(FixedDate).Add("2d")).To(DateMath.Now), r => r.To(DateMath.Now.Add(TimeSpan.FromDays(1)).Subtract("30m").RoundTo(DateMathTimeUnit.Hour)), r => r.From(DateMath.Anchored("2012-05-05").Add(TimeSpan.FromDays(1)).Subtract("1m")) ) .TimeZone("CET") .Aggregations(childAggs => childAggs .Terms("project_tags", avg => avg.Field(p => p.Tags)) ) )
Object Initializer syntax example
editnew DateRangeAggregation("projects_date_ranges") { Field = Field<Project>(p => p.StartedOn), Ranges = new List<DateRangeExpression> { new DateRangeExpression { From = DateMath.Anchored(FixedDate).Add("2d"), To = DateMath.Now }, new DateRangeExpression { To = DateMath.Now.Add(TimeSpan.FromDays(1)).Subtract("30m").RoundTo(DateMathTimeUnit.Hour) }, new DateRangeExpression { From = DateMath.Anchored("2012-05-05").Add(TimeSpan.FromDays(1)).Subtract("1m") } }, TimeZone = "CET", Aggregations = new TermsAggregation("project_tags") { Field = Field<Project>(p => p.Tags) } }
Example json output.
{ "projects_date_ranges": { "date_range": { "field": "startedOn", "ranges": [ { "to": "now", "from": "2015-06-06T12:01:02.123||+2d" }, { "to": "now+1d-30m/h" }, { "from": "2012-05-05||+1d-1m" } ], "time_zone": "CET" }, "aggs": { "project_tags": { "terms": { "field": "tags" } } } } }
Handling Responses
editThe AggregateDictionary found on `.Aggregations
on SearchResponse<T>
has several helper methods
so we can fetch our aggregation results easily in the correct type.
Be sure to read more about these helper methods
response.ShouldBeValid(); var dateHistogram = response.Aggregations.DateRange("projects_date_ranges"); dateHistogram.Should().NotBeNull(); dateHistogram.Buckets.Should().NotBeNull();
We specified three ranges so we expect to have three of them in the response
dateHistogram.Buckets.Count.Should().Be(3); foreach (var item in dateHistogram.Buckets) item.DocCount.Should().BeGreaterThan(0);