perf(table): prune by time range for filters on date_bin of the time index (#10345)

* perf: prune by time range for filters on date_bin of the time index

A filter on a view's date_bin(...) bucket column reaches the region scan
as date_bin(stride, ts) <op> literal. The time range extractor only
understood ts <op> literal, so such scans read every file.

date_bin floors to the bucket start, so date_bin(ts) <= ts <
date_bin(ts) + stride for any fixed-width stride and origin. Derive a
conservative time range from that for >, >=, <, <=, = and BETWEEN.

Signed-off-by: Floris Smit <florissmit10@gmail.com>

* fix(table): keep rows that date_bin truncates on coarse time indexes

DataFusion computes the date_bin bucket start in nanoseconds and truncates
it to the column unit, so on a TIMESTAMP(0|3|6) column the returned bucket
can be up to one unit below the true start. Widen the derived upper bound
by one unit on such columns.

Keep date_bin filters unsupported in extract_time_range_strict: a range
derived from them is up to a bucket wider than the filter, so timestamps
synthesized at its bounds may not satisfy it.

Signed-off-by: Floris Smit <florissmit10@gmail.com>

---------

Signed-off-by: Floris Smit <florissmit10@gmail.com>
This commit is contained in:
Floris Smit
2026-11-18 18:07:10 +00:00
committed by GitHub
parent 9cf76e20ad
commit 9543ef06d7
3 changed files with 896 additions and 12 deletions
+391 -12
View File
@@ -24,7 +24,7 @@ use datafusion::physical_optimizer::pruning::PruningPredicateBuilder;
use datafusion_common::ToDFSchema;
use datafusion_common::pruning::PruningStatistics;
use datafusion_common::tree_node::TreeNode;
use datafusion_expr::expr::{Expr, InList};
use datafusion_expr::expr::{Expr, InList, ScalarFunction};
use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
use datafusion_expr::{Between, BinaryExpr, Operator};
use datafusion_physical_expr::execution_props::ExecutionProps;
@@ -305,7 +305,9 @@ pub fn extract_time_range_strict(
// satisfying set (an `AND` side it cannot parse is dropped, which only
// widens), so intersecting extracted conjuncts stays an
// over-approximation.
match extract_time_range_from_expr(ts_col_name, ts_col_unit, expr) {
// Ranges derived from `date_bin` are skipped: they can be a bucket wider than
// the filter, so a timestamp synthesized at their bounds may not satisfy it.
match extract_time_range(ts_col_name, ts_col_unit, expr, DateBinFilters::Skip) {
Some(extracted) => {
range = Some(match range {
Some(acc) => acc.and(&extracted),
@@ -343,17 +345,37 @@ pub fn extract_time_range_from_expr(
ts_col_name: &str,
ts_col_unit: TimeUnit,
expr: &Expr,
) -> Option<TimestampRange> {
extract_time_range(ts_col_name, ts_col_unit, expr, DateBinFilters::Derive)
}
/// Whether a filter on `date_bin(stride, ts)` yields a range on `ts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DateBinFilters {
/// Derive a range that covers every satisfying row (see [`date_bin_stride`]).
Derive,
/// Treat the filter as unparsable.
Skip,
}
fn extract_time_range(
ts_col_name: &str,
ts_col_unit: TimeUnit,
expr: &Expr,
date_bin: DateBinFilters,
) -> Option<TimestampRange> {
match expr {
Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
extract_from_binary_expr(ts_col_name, ts_col_unit, left, op, right)
extract_from_binary_expr(ts_col_name, ts_col_unit, left, op, right, date_bin)
}
Expr::Between(Between {
expr,
negated,
low,
high,
}) => extract_from_between_expr(ts_col_name, ts_col_unit, expr, negated, low, high),
}) => {
extract_from_between_expr(ts_col_name, ts_col_unit, expr, negated, low, high, date_bin)
}
Expr::InList(InList {
expr,
list,
@@ -369,7 +391,14 @@ fn extract_from_binary_expr(
left: &Expr,
op: &Operator,
right: &Expr,
date_bin: DateBinFilters,
) -> Option<TimestampRange> {
if date_bin == DateBinFilters::Derive
&& let Some(range) =
extract_from_date_bin_comparison(ts_col_name, ts_col_unit, left, op, right)
{
return Some(range);
}
match op {
Operator::Eq => get_timestamp_filter(ts_col_name, left, right)
.and_then(|(ts, _)| ts.convert_to(ts_col_unit))
@@ -431,21 +460,119 @@ fn extract_from_binary_expr(
Operator::And => {
// instead of return none when failed to extract time range from left/right, we unwrap the none into
// `TimestampRange::min_to_max`.
let left = extract_time_range_from_expr(ts_col_name, ts_col_unit, left)
let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)
.unwrap_or_else(TimestampRange::min_to_max);
let right = extract_time_range_from_expr(ts_col_name, ts_col_unit, right)
let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)
.unwrap_or_else(TimestampRange::min_to_max);
Some(left.and(&right))
}
Operator::Or => {
let left = extract_time_range_from_expr(ts_col_name, ts_col_unit, left)?;
let right = extract_time_range_from_expr(ts_col_name, ts_col_unit, right)?;
let left = extract_time_range(ts_col_name, ts_col_unit, left, date_bin)?;
let right = extract_time_range(ts_col_name, ts_col_unit, right, date_bin)?;
Some(left.or(&right))
}
_ => None,
}
}
/// Returns the stride of `date_bin(stride, ts_col[, origin])`, converted to `unit`
/// and rounded up, if `expr` is that call with a literal, fixed-width stride.
///
/// `date_bin` floors a timestamp to the start of its bucket, so for every row
/// `bucket_start <= ts < bucket_start + stride`, whatever the origin. That lets a
/// filter on the bucket start bound the time index itself, which is what a
/// filter on a view's `date_bin(...) AS time` column becomes once it is pushed
/// below the view's aggregate.
///
/// This holds in nanoseconds. DataFusion computes the bucket start in
/// nanoseconds and truncates it to the column unit, so on a coarser column the
/// returned value can be up to one unit below the true start; see
/// [`date_bin_range`].
fn date_bin_stride(ts_col_name: &str, unit: TimeUnit, expr: &Expr) -> Option<i64> {
let Expr::ScalarFunction(ScalarFunction { func, args }) = expr else {
return None;
};
if func.name() != "date_bin" || !(2..=3).contains(&args.len()) {
return None;
}
let Expr::Column(col) = &args[1] else {
return None;
};
if col.name != ts_col_name {
return None;
}
let stride_ns: i128 = match &args[0] {
// Months have no fixed width.
Expr::Literal(ScalarValue::IntervalMonthDayNano(Some(v)), _) if v.months == 0 => {
v.days as i128 * 86_400_000_000_000 + v.nanoseconds as i128
}
Expr::Literal(ScalarValue::IntervalDayTime(Some(v)), _) => {
v.days as i128 * 86_400_000_000_000 + v.milliseconds as i128 * 1_000_000
}
_ => return None,
};
if stride_ns <= 0 {
return None;
}
let ns_per_unit = match unit {
TimeUnit::Second => 1_000_000_000,
TimeUnit::Millisecond => 1_000_000,
TimeUnit::Microsecond => 1_000,
TimeUnit::Nanosecond => 1,
};
i64::try_from((stride_ns + ns_per_unit - 1) / ns_per_unit).ok()
}
/// Extracts a time range from `date_bin(stride, ts_col) <op> literal`. The range
/// over-approximates the rows that satisfy the comparison (see [`date_bin_stride`]).
fn extract_from_date_bin_comparison(
ts_col_name: &str,
ts_col_unit: TimeUnit,
left: &Expr,
op: &Operator,
right: &Expr,
) -> Option<TimestampRange> {
// Normalize to `date_bin(...) <op> literal`.
let (bin, op, lit) = match (left, right) {
(bin, Expr::Literal(lit, _)) => (bin, *op, lit),
(Expr::Literal(lit, _), bin) => (bin, op.swap()?, lit),
_ => return None,
};
let stride = date_bin_stride(ts_col_name, ts_col_unit, bin)?;
return_none_if_utf8!(lit);
let bound = scalar_value_to_timestamp(lit, None)?;
date_bin_range(op, &bound, stride, ts_col_unit)
}
/// The range of `ts` for which `date_bin(stride, ts) <op> bound` can hold.
fn date_bin_range(
op: Operator,
bound: &Timestamp,
stride: i64,
unit: TimeUnit,
) -> Option<TimestampRange> {
// `bin >= bound` and `bin > bound` imply `ts >= bound`, because `ts >= bin`.
let lower = || bound.convert_to_ceil(unit).map(TimestampRange::from_start);
// `bin <= bound` and `bin < bound` imply `ts < bound + stride`, because `ts < bin + stride`.
// On a column coarser than nanoseconds, the returned `bin` is truncated from the true
// bucket start and can be up to one unit below it, so widen the end by one unit.
let slack = if unit == TimeUnit::Nanosecond { 0 } else { 1 };
let upper = || {
let end = bound
.convert_to_ceil(unit)?
.value()
.checked_add(stride)?
.checked_add(slack)?;
Some(TimestampRange::until_end(Timestamp::new(end, unit), false))
};
match op {
Operator::Gt | Operator::GtEq => lower(),
Operator::Lt | Operator::LtEq => upper(),
Operator::Eq => Some(lower()?.and(&upper()?)),
_ => None,
}
}
fn get_timestamp_filter(ts_col_name: &str, left: &Expr, right: &Expr) -> Option<(Timestamp, bool)> {
let (col, lit, reverse) = match (left, right) {
(Expr::Column(column), Expr::Literal(scalar, _)) => (column, scalar, false),
@@ -469,7 +596,39 @@ fn extract_from_between_expr(
negated: &bool,
low: &Expr,
high: &Expr,
date_bin: DateBinFilters,
) -> Option<TimestampRange> {
if *negated {
return None;
}
if date_bin == DateBinFilters::Derive
&& let Some(stride) = date_bin_stride(ts_col_name, ts_col_unit, expr)
{
// `low <= date_bin(...) <= high`
let (Expr::Literal(low, _), Expr::Literal(high, _)) = (low, high) else {
return None;
};
return_none_if_utf8!(low);
return_none_if_utf8!(high);
let low = date_bin_range(
Operator::GtEq,
&scalar_value_to_timestamp(low, None)?,
stride,
ts_col_unit,
);
let high = date_bin_range(
Operator::LtEq,
&scalar_value_to_timestamp(high, None)?,
stride,
ts_col_unit,
);
return Some(
low.unwrap_or_else(TimestampRange::min_to_max)
.and(&high.unwrap_or_else(TimestampRange::min_to_max)),
);
}
let Expr::Column(col) = expr else {
return None;
};
@@ -477,10 +636,6 @@ fn extract_from_between_expr(
return None;
}
if *negated {
return None;
}
match (low, high) {
(Expr::Literal(low, _), Expr::Literal(high, _)) => {
return_none_if_utf8!(low);
@@ -554,6 +709,209 @@ mod tests {
);
}
fn date_bin(stride: Expr) -> Expr {
datafusion::functions::datetime::date_bin().call(vec![stride, col("ts")])
}
fn ms(v: i64) -> Expr {
lit(ScalarValue::TimestampMillisecond(Some(v), None))
}
fn minute() -> Expr {
lit(ScalarValue::new_interval_mdn(0, 0, 60_000_000_000))
}
#[test]
fn test_date_bin() {
// Upper bounds on a coarser-than-ns column are widened by one unit, because
// `date_bin` truncates its nanosecond bucket start to the column unit.
let t = Timestamp::new_millisecond;
// date_bin(1m, ts) >= 120_000ms => ts >= 120_000ms
check_build_predicate(
date_bin(minute()).gt_eq(ms(120_000)),
TimestampRange::from_start(t(120_000)),
);
// date_bin(1m, ts) > 120_000ms => ts > 120_000ms, widened to ts >= 120_000ms
check_build_predicate(
date_bin(minute()).gt(ms(120_000)),
TimestampRange::from_start(t(120_000)),
);
// date_bin(1m, ts) < 120_000ms => ts < 180_001ms
check_build_predicate(
date_bin(minute()).lt(ms(120_000)),
TimestampRange::until_end(t(180_001), false),
);
// date_bin(1m, ts) <= 120_000ms => ts < 180_001ms
check_build_predicate(
date_bin(minute()).lt_eq(ms(120_000)),
TimestampRange::until_end(t(180_001), false),
);
// 120_000ms <= date_bin(1m, ts) => ts >= 120_000ms
check_build_predicate(
ms(120_000).lt_eq(date_bin(minute())),
TimestampRange::from_start(t(120_000)),
);
// date_bin(1m, ts) = 120_000ms => 120_000ms <= ts < 180_001ms
check_build_predicate(
date_bin(minute()).eq(ms(120_000)),
TimestampRange::new(t(120_000), t(180_001)).unwrap(),
);
// date_bin(1m, ts) BETWEEN 60_000ms AND 120_000ms => 60_000ms <= ts < 180_001ms
check_build_predicate(
date_bin(minute()).between(ms(60_000), ms(120_000)),
TimestampRange::new(t(60_000), t(180_001)).unwrap(),
);
// Combined with other conjuncts.
check_build_predicate(
date_bin(minute())
.gt_eq(ms(60_000))
.and(date_bin(minute()).lt(ms(120_000)))
.and(col("v").gt(lit(1))),
TimestampRange::new(t(60_000), t(180_001)).unwrap(),
);
// An origin argument doesn't change the bounds.
check_build_predicate(
datafusion::functions::datetime::date_bin()
.call(vec![minute(), col("ts"), ms(17)])
.gt_eq(ms(120_000)),
TimestampRange::from_start(t(120_000)),
);
// A month stride has no fixed width: no range for the upper bound.
check_build_predicate(
date_bin(lit(ScalarValue::new_interval_mdn(1, 0, 0))).lt(ms(120_000)),
TimestampRange::min_to_max(),
);
// Other columns are ignored.
check_build_predicate(
datafusion::functions::datetime::date_bin()
.call(vec![minute(), col("other")])
.gt_eq(ms(120_000)),
TimestampRange::min_to_max(),
);
// An upper bound that overflows leaves the range unbounded.
check_build_predicate(
date_bin(minute()).lt_eq(ms(i64::MAX - 1)),
TimestampRange::min_to_max(),
);
}
/// Evaluates `date_bin` with DataFusion over a grid of timestamps, then checks
/// that every row satisfying a comparison on its result lies in the extracted
/// range. Covers coarse column units, strides and origins that are not a whole
/// number of column units, and negative timestamps.
#[tokio::test]
async fn test_date_bin_range_keeps_satisfying_rows() {
/// Whether the comparison holds for a `date_bin` result.
type BinHolds = Box<dyn Fn(i64) -> bool>;
use datafusion::prelude::SessionContext;
use datafusion_expr::cast;
use datatypes::arrow::array::{AsArray, Int64Array};
use datatypes::arrow::datatypes::{Int64Type, TimeUnit as ArrowTimeUnit};
let units = [
(TimeUnit::Second, ArrowTimeUnit::Second, 1_000_000_000i64),
(TimeUnit::Millisecond, ArrowTimeUnit::Millisecond, 1_000_000),
(TimeUnit::Microsecond, ArrowTimeUnit::Microsecond, 1_000),
];
let ctx = SessionContext::new();
for (unit, arrow_unit, ns_per_unit) in units {
let ts_lit = |v: i64| {
lit(match unit {
TimeUnit::Second => ScalarValue::TimestampSecond(Some(v), None),
TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(Some(v), None),
TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(Some(v), None),
TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(Some(v), None),
})
};
let ts_type = DataType::Timestamp(arrow_unit, None);
let ts_array = datatypes::arrow::compute::cast(
&Int64Array::from((-30..=30).collect::<Vec<i64>>()),
&ts_type,
)
.unwrap();
let schema = Arc::new(Schema::new(vec![Field::new("ts", ts_type, false)]));
let batch = RecordBatch::try_new(schema, vec![ts_array]).unwrap();
let strides_ns = [
ns_per_unit,
ns_per_unit * 3,
ns_per_unit / 2,
ns_per_unit * 13 / 10,
ns_per_unit * 26 / 10,
];
let origins_ns = [
None,
Some(0),
Some(ns_per_unit / 2),
Some(-ns_per_unit * 7 / 3),
];
for stride_ns in strides_ns {
for origin_ns in origins_ns {
let mut args = vec![
lit(ScalarValue::new_interval_mdn(0, 0, stride_ns)),
col("ts"),
];
if let Some(origin) = origin_ns {
args.push(lit(ScalarValue::TimestampNanosecond(Some(origin), None)));
}
let bin = datafusion::functions::datetime::date_bin().call(args);
// (ts, date_bin(ts)), both in the column unit.
let rows: Vec<(i64, i64)> = ctx
.read_batch(batch.clone())
.unwrap()
.select(vec![
cast(col("ts"), DataType::Int64),
cast(bin.clone(), DataType::Int64),
])
.unwrap()
.collect()
.await
.unwrap()
.iter()
.flat_map(|b| {
let ts = b.column(0).as_primitive::<Int64Type>();
let bins = b.column(1).as_primitive::<Int64Type>();
ts.values()
.iter()
.copied()
.zip(bins.values().iter().copied())
.collect::<Vec<_>>()
})
.collect();
assert_eq!(rows.len(), 61);
for c in -35..=35 {
let cases: Vec<(Expr, BinHolds)> = vec![
(bin.clone().eq(ts_lit(c)), Box::new(move |b| b == c)),
(bin.clone().lt(ts_lit(c)), Box::new(move |b| b < c)),
(bin.clone().lt_eq(ts_lit(c)), Box::new(move |b| b <= c)),
(bin.clone().gt(ts_lit(c)), Box::new(move |b| b > c)),
(bin.clone().gt_eq(ts_lit(c)), Box::new(move |b| b >= c)),
(ts_lit(c).gt_eq(bin.clone()), Box::new(move |b| c >= b)),
(
bin.clone().between(ts_lit(c), ts_lit(c + 2)),
Box::new(move |b| c <= b && b <= c + 2),
),
];
for (expr, holds) in cases {
let range =
build_time_range_predicate("ts", unit, std::slice::from_ref(&expr));
for &(ts, b) in &rows {
assert!(
!holds(b) || range.contains(&Timestamp::new(ts, unit)),
"{expr} holds for ts={ts} (bin={b}, {unit:?}, stride={stride_ns}ns, origin={origin_ns:?}ns) but {range:?} excludes it",
);
}
}
}
}
}
}
}
#[test]
fn test_gt() {
// ts > 1ms
@@ -801,6 +1159,27 @@ mod tests {
extract(&[col("ts").gt_eq(col("t2"))]),
TimeRangeExtraction::Unsupported
);
// A range derived from `date_bin` over-approximates by up to a bucket, so a
// timestamp synthesized from its bounds may fail the filter: refuse it.
assert_eq!(
extract(&[date_bin(minute()).gt(ts_lit(60_000))]),
TimeRangeExtraction::Unsupported
);
assert_eq!(
extract(&[date_bin(minute()).between(ts_lit(0), ts_lit(60_000))]),
TimeRangeExtraction::Unsupported
);
// Under AND it is dropped like any other unparsable side.
assert_eq!(
extract(&[col("ts")
.lt(ts_lit(2000))
.and(date_bin(minute()).gt_eq(ts_lit(60_000)))]),
TimeRangeExtraction::Extracted(TimestampRange::until_end(
Timestamp::new_millisecond(2000),
false
))
);
}
async fn gen_test_parquet_file(dir: &TempDir, cnt: usize) -> (String, Arc<Schema>) {
@@ -0,0 +1,348 @@
-- A filter on `date_bin(stride, ts)` bounds the time index, so it prunes SST files.
-- This is what a filter on a view's `date_bin(...) AS time` column becomes once it is
-- pushed below the view's aggregate.
CREATE TABLE
IF NOT EXISTS `power` (
`topic` STRING NULL,
`p` DOUBLE NULL,
`ts` TIMESTAMP(9) NOT NULL,
TIME INDEX (`ts`),
) ENGINE = mito
WITH
(append_mode = 'true');
Affected Rows: 0
-- One SST file per day.
INSERT INTO
power
VALUES
("a", 1, "2023-06-10 10:00:10"),
("a", 3, "2023-06-10 10:00:50"),
("b", 5, "2023-06-10 23:59:59");
Affected Rows: 3
ADMIN FLUSH_TABLE ('power');
+----------------------------+
| ADMIN FLUSH_TABLE('power') |
+----------------------------+
| 0 |
+----------------------------+
INSERT INTO
power
VALUES
("a", 10, "2023-06-11 00:00:00"),
("a", 20, "2023-06-11 00:00:30"),
("b", 30, "2023-06-11 12:00:00");
Affected Rows: 3
ADMIN FLUSH_TABLE ('power');
+----------------------------+
| ADMIN FLUSH_TABLE('power') |
+----------------------------+
| 0 |
+----------------------------+
INSERT INTO
power
VALUES
("a", 100, "2023-06-12 00:00:00"),
("b", 200, "2023-06-12 08:30:00");
Affected Rows: 2
ADMIN FLUSH_TABLE ('power');
+----------------------------+
| ADMIN FLUSH_TABLE('power') |
+----------------------------+
| 0 |
+----------------------------+
CREATE VIEW power_per_minute AS
SELECT
date_bin('1 minute' :: INTERVAL, ts) AS time,
topic,
avg(p) AS p
FROM
power
GROUP BY
time,
topic;
Affected Rows: 0
SELECT * FROM power_per_minute WHERE time >= '2023-06-11 00:00:00' ORDER BY time, topic;
+---------------------+-------+-------+
| time | topic | p |
+---------------------+-------+-------+
| 2023-06-11T00:00:00 | a | 15.0 |
| 2023-06-11T12:00:00 | b | 30.0 |
| 2023-06-12T00:00:00 | a | 100.0 |
| 2023-06-12T08:30:00 | b | 200.0 |
+---------------------+-------+-------+
SELECT * FROM power_per_minute WHERE time > '2023-06-11 00:00:00' ORDER BY time, topic;
+---------------------+-------+-------+
| time | topic | p |
+---------------------+-------+-------+
| 2023-06-11T12:00:00 | b | 30.0 |
| 2023-06-12T00:00:00 | a | 100.0 |
| 2023-06-12T08:30:00 | b | 200.0 |
+---------------------+-------+-------+
-- The bucket starting at 2023-06-10 23:59:00 holds a row from the first file.
SELECT * FROM power_per_minute WHERE time < '2023-06-11 00:00:00' ORDER BY time, topic;
+---------------------+-------+-----+
| time | topic | p |
+---------------------+-------+-----+
| 2023-06-10T10:00:00 | a | 2.0 |
| 2023-06-10T23:59:00 | b | 5.0 |
+---------------------+-------+-----+
SELECT * FROM power_per_minute WHERE time <= '2023-06-10 23:59:00' ORDER BY time, topic;
+---------------------+-------+-----+
| time | topic | p |
+---------------------+-------+-----+
| 2023-06-10T10:00:00 | a | 2.0 |
| 2023-06-10T23:59:00 | b | 5.0 |
+---------------------+-------+-----+
SELECT * FROM power_per_minute WHERE time = '2023-06-11 00:00:00' ORDER BY time, topic;
+---------------------+-------+------+
| time | topic | p |
+---------------------+-------+------+
| 2023-06-11T00:00:00 | a | 15.0 |
+---------------------+-------+------+
SELECT * FROM power_per_minute WHERE time BETWEEN '2023-06-11 00:00:00' AND '2023-06-11 23:59:00' ORDER BY time, topic;
+---------------------+-------+------+
| time | topic | p |
+---------------------+-------+------+
| 2023-06-11T00:00:00 | a | 15.0 |
| 2023-06-11T12:00:00 | b | 30.0 |
+---------------------+-------+------+
SELECT * FROM power_per_minute WHERE '2023-06-12 00:00:00' <= time ORDER BY time, topic;
+---------------------+-------+-------+
| time | topic | p |
+---------------------+-------+-------+
| 2023-06-12T00:00:00 | a | 100.0 |
| 2023-06-12T08:30:00 | b | 200.0 |
+---------------------+-------+-------+
-- Only the file of 2023-06-12 is scanned.
-- SQLNESS REPLACE (-+) -
-- SQLNESS REPLACE (\s\s+) _
-- SQLNESS REPLACE (metrics.*) REDACTED
-- SQLNESS REPLACE (peers.*) REDACTED
-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED
-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED
-- SQLNESS REPLACE (Hash.*) REDACTED
-- SQLNESS REPLACE \\?"(file_summary|max_part_range)\\?":.* "$1":REDACTED
EXPLAIN ANALYZE SELECT count(*) FROM power_per_minute WHERE time >= '2023-06-12 00:00:00';
+-+-+-+
| stage | node | plan_|
+-+-+-+
| 0_| 0_|_CooperativeExec REDACTED
|_|_|_MergeScanExec: REDACTED
|_|_|_|
| 1_| 0_|_ProjectionExec: expr=[count(Int64(1))@0 as count(*)] REDACTED
|_|_|_AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1))] REDACTED
|_|_|_CoalescePartitionsExec REDACTED
|_|_|_AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))] REDACTED
|_|_|_ProjectionExec: expr=[] REDACTED
|_|_|_AggregateExec: mode=FinalPartitioned, gby=[date_bin(Utf8("1 minute"),greptime.public.power.ts)@0 as date_bin(Utf8("1 minute"),greptime.public.power.ts), topic@1 as topic], aggr=[] REDACTED
|_|_|_RepartitionExec: partitioning=REDACTED
|_|_|_AggregateExec: mode=Partial, gby=[date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }, ts@1) as date_bin(Utf8("1 minute"),greptime.public.power.ts), topic@0 as topic], aggr=[] REDACTED
|_|_|_FilterExec: date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }, ts@1) >= 1686528000000000000 REDACTED
|_|_|_UnorderedScan: region=REDACTED, "partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["topic", "ts"], "filters": ["date_bin(IntervalMonthDayNano(\"IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }\"), ts) >= TimestampNanosecond(1686528000000000000, None)"], "time_range": "TimestampRange{[1686528000000000000ns,#)}", "file_summary":REDACTED
|_|_|_|
|_|_| Total rows: 1_|
+-+-+-+
-- The files of 2023-06-10 and 2023-06-11 are scanned: the upper bound is widened by one stride.
-- SQLNESS REPLACE (-+) -
-- SQLNESS REPLACE (\s\s+) _
-- SQLNESS REPLACE (metrics.*) REDACTED
-- SQLNESS REPLACE (peers.*) REDACTED
-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED
-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED
-- SQLNESS REPLACE (Hash.*) REDACTED
-- SQLNESS REPLACE \\?"(file_summary|max_part_range)\\?":.* "$1":REDACTED
EXPLAIN ANALYZE SELECT count(*) FROM power_per_minute WHERE time < '2023-06-11 00:00:00';
+-+-+-+
| stage | node | plan_|
+-+-+-+
| 0_| 0_|_CooperativeExec REDACTED
|_|_|_MergeScanExec: REDACTED
|_|_|_|
| 1_| 0_|_ProjectionExec: expr=[count(Int64(1))@0 as count(*)] REDACTED
|_|_|_AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1))] REDACTED
|_|_|_CoalescePartitionsExec REDACTED
|_|_|_AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1))] REDACTED
|_|_|_ProjectionExec: expr=[] REDACTED
|_|_|_AggregateExec: mode=FinalPartitioned, gby=[date_bin(Utf8("1 minute"),greptime.public.power.ts)@0 as date_bin(Utf8("1 minute"),greptime.public.power.ts), topic@1 as topic], aggr=[] REDACTED
|_|_|_RepartitionExec: partitioning=REDACTED
|_|_|_AggregateExec: mode=Partial, gby=[date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }, ts@1) as date_bin(Utf8("1 minute"),greptime.public.power.ts), topic@0 as topic], aggr=[] REDACTED
|_|_|_FilterExec: date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }, ts@1) < 1686441600000000000 REDACTED
|_|_|_UnorderedScan: region=REDACTED, "partition_count":{"count":2, "mem_ranges":0, "files":2, "file_ranges":2}, "projection": ["topic", "ts"], "filters": ["date_bin(IntervalMonthDayNano(\"IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 60000000000 }\"), ts) < TimestampNanosecond(1686441600000000000, None)"], "time_range": "TimestampRange{[#,1686441660000000000ns)}", "file_summary":REDACTED
|_|_|_|
|_|_| Total rows: 1_|
+-+-+-+
DROP VIEW power_per_minute;
Affected Rows: 0
DROP TABLE power;
Affected Rows: 0
-- On a coarser time index, `date_bin` truncates its nanosecond bucket start to the
-- column unit, so the returned bucket can start up to one unit before the true one.
-- Each row below sits in its own file, which the upper bound must not prune.
CREATE TABLE
IF NOT EXISTS `power_ms` (
`p` DOUBLE NULL,
`ts` TIMESTAMP(3) NOT NULL,
TIME INDEX (`ts`),
) ENGINE = mito
WITH
(append_mode = 'true');
Affected Rows: 0
INSERT INTO power_ms VALUES (1, "2023-06-10 00:00:00.001");
Affected Rows: 1
ADMIN FLUSH_TABLE ('power_ms');
+-------------------------------+
| ADMIN FLUSH_TABLE('power_ms') |
+-------------------------------+
| 0 |
+-------------------------------+
INSERT INTO power_ms VALUES (2, "2023-06-10 00:00:00.010");
Affected Rows: 1
ADMIN FLUSH_TABLE ('power_ms');
+-------------------------------+
| ADMIN FLUSH_TABLE('power_ms') |
+-------------------------------+
| 0 |
+-------------------------------+
INSERT INTO power_ms VALUES (3, "2023-06-11 00:00:00");
Affected Rows: 1
ADMIN FLUSH_TABLE ('power_ms');
+-------------------------------+
| ADMIN FLUSH_TABLE('power_ms') |
+-------------------------------+
| 0 |
+-------------------------------+
-- An origin half a millisecond off: the bucket of 00:00:00.001 truly starts at
-- 00:00:00.0005 and is returned as 00:00:00.000.
CREATE VIEW power_ms_origin AS
SELECT
date_bin(
'1 millisecond' :: INTERVAL,
ts,
'2023-06-10 00:00:00.0005' :: TIMESTAMP(9)
) AS time,
p
FROM
power_ms;
Affected Rows: 0
SELECT * FROM power_ms_origin WHERE time = '2023-06-10 00:00:00' ORDER BY time;
+---------------------+-----+
| time | p |
+---------------------+-----+
| 2023-06-10T00:00:00 | 1.0 |
+---------------------+-----+
SELECT * FROM power_ms_origin WHERE time <= '2023-06-10 00:00:00' ORDER BY time;
+---------------------+-----+
| time | p |
+---------------------+-----+
| 2023-06-10T00:00:00 | 1.0 |
+---------------------+-----+
SELECT * FROM power_ms_origin WHERE time BETWEEN '2023-06-09 00:00:00' AND '2023-06-10 00:00:00' ORDER BY time;
+---------------------+-----+
| time | p |
+---------------------+-----+
| 2023-06-10T00:00:00 | 1.0 |
+---------------------+-----+
-- A stride of 2.6 ms from midnight: the bucket of 00:00:00.010 truly starts at
-- 00:00:00.0078 and is returned as 00:00:00.007.
CREATE VIEW power_ms_stride AS
SELECT
date_bin(
'2600 microseconds' :: INTERVAL,
ts,
'2023-06-10 00:00:00' :: TIMESTAMP(9)
) AS time,
p
FROM
power_ms;
Affected Rows: 0
SELECT * FROM power_ms_stride WHERE time = '2023-06-10 00:00:00.007' ORDER BY time;
+-------------------------+-----+
| time | p |
+-------------------------+-----+
| 2023-06-10T00:00:00.007 | 2.0 |
+-------------------------+-----+
SELECT * FROM power_ms_stride WHERE time <= '2023-06-10 00:00:00.007' ORDER BY time;
+-------------------------+-----+
| time | p |
+-------------------------+-----+
| 2023-06-10T00:00:00 | 1.0 |
| 2023-06-10T00:00:00.007 | 2.0 |
+-------------------------+-----+
DROP VIEW power_ms_origin;
Affected Rows: 0
DROP VIEW power_ms_stride;
Affected Rows: 0
DROP TABLE power_ms;
Affected Rows: 0
@@ -0,0 +1,157 @@
-- A filter on `date_bin(stride, ts)` bounds the time index, so it prunes SST files.
-- This is what a filter on a view's `date_bin(...) AS time` column becomes once it is
-- pushed below the view's aggregate.
CREATE TABLE
IF NOT EXISTS `power` (
`topic` STRING NULL,
`p` DOUBLE NULL,
`ts` TIMESTAMP(9) NOT NULL,
TIME INDEX (`ts`),
) ENGINE = mito
WITH
(append_mode = 'true');
-- One SST file per day.
INSERT INTO
power
VALUES
("a", 1, "2023-06-10 10:00:10"),
("a", 3, "2023-06-10 10:00:50"),
("b", 5, "2023-06-10 23:59:59");
ADMIN FLUSH_TABLE ('power');
INSERT INTO
power
VALUES
("a", 10, "2023-06-11 00:00:00"),
("a", 20, "2023-06-11 00:00:30"),
("b", 30, "2023-06-11 12:00:00");
ADMIN FLUSH_TABLE ('power');
INSERT INTO
power
VALUES
("a", 100, "2023-06-12 00:00:00"),
("b", 200, "2023-06-12 08:30:00");
ADMIN FLUSH_TABLE ('power');
CREATE VIEW power_per_minute AS
SELECT
date_bin('1 minute' :: INTERVAL, ts) AS time,
topic,
avg(p) AS p
FROM
power
GROUP BY
time,
topic;
SELECT * FROM power_per_minute WHERE time >= '2023-06-11 00:00:00' ORDER BY time, topic;
SELECT * FROM power_per_minute WHERE time > '2023-06-11 00:00:00' ORDER BY time, topic;
-- The bucket starting at 2023-06-10 23:59:00 holds a row from the first file.
SELECT * FROM power_per_minute WHERE time < '2023-06-11 00:00:00' ORDER BY time, topic;
SELECT * FROM power_per_minute WHERE time <= '2023-06-10 23:59:00' ORDER BY time, topic;
SELECT * FROM power_per_minute WHERE time = '2023-06-11 00:00:00' ORDER BY time, topic;
SELECT * FROM power_per_minute WHERE time BETWEEN '2023-06-11 00:00:00' AND '2023-06-11 23:59:00' ORDER BY time, topic;
SELECT * FROM power_per_minute WHERE '2023-06-12 00:00:00' <= time ORDER BY time, topic;
-- Only the file of 2023-06-12 is scanned.
-- SQLNESS REPLACE (-+) -
-- SQLNESS REPLACE (\s\s+) _
-- SQLNESS REPLACE (metrics.*) REDACTED
-- SQLNESS REPLACE (peers.*) REDACTED
-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED
-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED
-- SQLNESS REPLACE (Hash.*) REDACTED
-- SQLNESS REPLACE \\?"(file_summary|max_part_range)\\?":.* "$1":REDACTED
EXPLAIN ANALYZE SELECT count(*) FROM power_per_minute WHERE time >= '2023-06-12 00:00:00';
-- The files of 2023-06-10 and 2023-06-11 are scanned: the upper bound is widened by one stride.
-- SQLNESS REPLACE (-+) -
-- SQLNESS REPLACE (\s\s+) _
-- SQLNESS REPLACE (metrics.*) REDACTED
-- SQLNESS REPLACE (peers.*) REDACTED
-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED
-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED
-- SQLNESS REPLACE (Hash.*) REDACTED
-- SQLNESS REPLACE \\?"(file_summary|max_part_range)\\?":.* "$1":REDACTED
EXPLAIN ANALYZE SELECT count(*) FROM power_per_minute WHERE time < '2023-06-11 00:00:00';
DROP VIEW power_per_minute;
DROP TABLE power;
-- On a coarser time index, `date_bin` truncates its nanosecond bucket start to the
-- column unit, so the returned bucket can start up to one unit before the true one.
-- Each row below sits in its own file, which the upper bound must not prune.
CREATE TABLE
IF NOT EXISTS `power_ms` (
`p` DOUBLE NULL,
`ts` TIMESTAMP(3) NOT NULL,
TIME INDEX (`ts`),
) ENGINE = mito
WITH
(append_mode = 'true');
INSERT INTO power_ms VALUES (1, "2023-06-10 00:00:00.001");
ADMIN FLUSH_TABLE ('power_ms');
INSERT INTO power_ms VALUES (2, "2023-06-10 00:00:00.010");
ADMIN FLUSH_TABLE ('power_ms');
INSERT INTO power_ms VALUES (3, "2023-06-11 00:00:00");
ADMIN FLUSH_TABLE ('power_ms');
-- An origin half a millisecond off: the bucket of 00:00:00.001 truly starts at
-- 00:00:00.0005 and is returned as 00:00:00.000.
CREATE VIEW power_ms_origin AS
SELECT
date_bin(
'1 millisecond' :: INTERVAL,
ts,
'2023-06-10 00:00:00.0005' :: TIMESTAMP(9)
) AS time,
p
FROM
power_ms;
SELECT * FROM power_ms_origin WHERE time = '2023-06-10 00:00:00' ORDER BY time;
SELECT * FROM power_ms_origin WHERE time <= '2023-06-10 00:00:00' ORDER BY time;
SELECT * FROM power_ms_origin WHERE time BETWEEN '2023-06-09 00:00:00' AND '2023-06-10 00:00:00' ORDER BY time;
-- A stride of 2.6 ms from midnight: the bucket of 00:00:00.010 truly starts at
-- 00:00:00.0078 and is returned as 00:00:00.007.
CREATE VIEW power_ms_stride AS
SELECT
date_bin(
'2600 microseconds' :: INTERVAL,
ts,
'2023-06-10 00:00:00' :: TIMESTAMP(9)
) AS time,
p
FROM
power_ms;
SELECT * FROM power_ms_stride WHERE time = '2023-06-10 00:00:00.007' ORDER BY time;
SELECT * FROM power_ms_stride WHERE time <= '2023-06-10 00:00:00.007' ORDER BY time;
DROP VIEW power_ms_origin;
DROP VIEW power_ms_stride;
DROP TABLE power_ms;