diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index d3fa983ff9e841..88d135fd1681bb 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -96,8 +96,6 @@ export const evaluateAlert = { ); }); }); + + describe('when passed a timeframe of 1 hour', () => { + const testTimeframe = { + start: moment().subtract(1, 'hour').valueOf(), + end: moment().valueOf(), + }; + const searchBodyWithoutGroupBy = getElasticsearchMetricQuery( + expressionParams, + timefield, + testTimeframe + ); + const searchBodyWithGroupBy = getElasticsearchMetricQuery( + expressionParams, + timefield, + testTimeframe, + groupBy + ); + test("generates 1 hour's worth of buckets", () => { + // @ts-ignore + expect(searchBodyWithoutGroupBy.aggs.aggregatedIntervals.date_range.ranges.length).toBe(60); + expect( + // @ts-ignore + searchBodyWithGroupBy.aggs.groupings.aggs.aggregatedIntervals.date_range.ranges.length + ).toBe(60); + }); + }); }); diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts index cde84b217be950..66e112640c3576 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts @@ -76,12 +76,13 @@ export const getElasticsearchMetricQuery = ( aggregatedIntervals: { date_range: { field: timefield, - ranges: [ - { - from: to - intervalAsMS - deliveryDelay, - to: to - deliveryDelay, - }, - ], + // Generate an array of buckets, starting at `from` and ending at `to` + // This is usually only necessary for alert previews or rate aggs. Most alert evaluations + // will generate only one bucket from this logic. + ranges: Array.from(Array(Math.floor((to - from) / intervalAsMS)), (_, i) => ({ + from: from + intervalAsMS * i - deliveryDelay, + to: from + intervalAsMS * (i + 1) - deliveryDelay, + })), }, aggregations, },