mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-04 03:35:36 +08:00
Run windows over the rows they see in filters and grouped aggregates
This commit is contained in:
@@ -584,6 +584,11 @@ export const groupBy: {
|
||||
* Computes aggregates per group: one row per distinct key, in order of first
|
||||
* appearance, with the key columns first.
|
||||
*
|
||||
* **Details**
|
||||
*
|
||||
* An aggregate's argument is evaluated per group: window functions in it
|
||||
* (`Expr.cumSum`, `Expr.over`, …) see only the group's rows, in row order.
|
||||
*
|
||||
* @stability experimental
|
||||
* @category grouping
|
||||
* @since 4.1.5
|
||||
|
||||
@@ -143,7 +143,10 @@ export const show = (node: Node): string => {
|
||||
export interface Context {
|
||||
readonly length: number
|
||||
readonly column: (name: string) => V.Vector
|
||||
/** The partitions of an enclosing `Over`: window functions run per partition. */
|
||||
/**
|
||||
* The partitions of an enclosing `Over` or grouped aggregate: window
|
||||
* functions run per partition, and aggregates broadcast over it.
|
||||
*/
|
||||
readonly partition?: W.Partition | undefined
|
||||
}
|
||||
|
||||
@@ -188,17 +191,18 @@ export const evaluate = (node: Node, ctx: Context): K.Value => {
|
||||
case "Literal":
|
||||
return node.type === undefined || node.value === null ? literal(node.value) : literalOfType(node.value, node.type)
|
||||
case "AggregateCall": {
|
||||
// Inside `over`: the partition's aggregate on each of its rows.
|
||||
// Inside `over` or an aggregate: the partition's aggregate on each of its rows.
|
||||
if (ctx.partition === undefined) return V.fail(`aggregate ${show(node)} can only be used in agg or over`)
|
||||
if (node.arg === undefined && node.fn !== "count") return V.fail(`${node.fn} needs an argument`)
|
||||
const arg = node.arg === undefined ? undefined : evaluateColumn(node.arg, { ...ctx, partition: undefined })
|
||||
const arg = node.arg === undefined ? undefined : evaluateColumn(node.arg, ctx)
|
||||
const values = Agg.aggregate(node.arg === undefined ? "len" : node.fn, arg, ctx.partition)
|
||||
return K.column(V.take(values, ctx.partition.ids))
|
||||
}
|
||||
case "Call":
|
||||
return evaluateCall(node, ctx)
|
||||
case "Over": {
|
||||
const keys = node.partitionBy.map((k) => evaluateColumn(k, { ...ctx, partition: undefined }))
|
||||
const keys = node.partitionBy.map((k) => evaluateColumn(k, ctx))
|
||||
if (ctx.partition !== undefined) keys.unshift(V.i32(S.int32, ctx.partition.ids))
|
||||
const g = Hash.groups(keys, ctx.length)
|
||||
return evaluate(node.expression, { ...ctx, partition: { ids: g.ids, count: g.count } })
|
||||
}
|
||||
@@ -456,8 +460,7 @@ const evaluateCall = (node: Plan.Call, ctx: Context): K.Value => {
|
||||
case "rollingMean":
|
||||
case "rollingMin":
|
||||
case "rollingMax": {
|
||||
// The argument is evaluated over all rows, the window per partition.
|
||||
const x = K.materialize(evaluate(node.args[0], { ...ctx, partition: undefined }), n)
|
||||
const x = K.materialize(evaluate(node.args[0], ctx), n)
|
||||
const p = ctx.partition ?? W.whole(n)
|
||||
switch (node.fn) {
|
||||
case "cumSum":
|
||||
|
||||
@@ -344,7 +344,7 @@ const aggregateColumns = (
|
||||
aggs: { readonly [name: string]: E.Node },
|
||||
grouping: Agg.Grouping
|
||||
): Array<Column> => {
|
||||
const ctx = context(self)
|
||||
const ctx: E.Context = { ...context(self), partition: grouping }
|
||||
return Object.keys(aggs).map((name) => {
|
||||
const node = aggs[name]
|
||||
if (node._tag !== "AggregateCall") return V.fail(`${name} is not an aggregate expression`)
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
* Execution is a post-order walk that calls the frame operations. Before it,
|
||||
* `optimize` rewrites the plan so less work happens:
|
||||
*
|
||||
* - predicates move below the operations they commute with (sorts,
|
||||
* projections, derived columns they don't read, group keys, either side of
|
||||
* a join, every input of a concat), and filters that meet merge;
|
||||
* - row-wise predicates move below the operations they commute with
|
||||
* (sorts, projections, derived columns they don't read, group keys, either
|
||||
* side of a join, every input of a concat), and filters that meet merge;
|
||||
* predicates with windows stay where they are;
|
||||
* - slices move below row-wise operations, and a slice of a sort becomes a
|
||||
* top-k selection;
|
||||
* - columns nothing reads are dropped at the inputs, and derived columns and
|
||||
@@ -232,9 +233,14 @@ const pushFilters = (node: Node): Node => {
|
||||
const filtered = (input: Node, predicates: ReadonlyArray<Plan.Expression>): Node =>
|
||||
predicates.length === 0 ? input : { _tag: "Filter", input, predicate: and(predicates) }
|
||||
|
||||
/** Places each predicate as deep as it can go below `node`. */
|
||||
/**
|
||||
* Places each predicate as deep as it can go below `node`. Predicates that
|
||||
* are not row-wise (windows) depend on exactly the rows they see, so a set
|
||||
* containing one stays where it is.
|
||||
*/
|
||||
const push = (node: Node, predicates: ReadonlyArray<Plan.Expression>): Node => {
|
||||
if (predicates.length === 0) return node
|
||||
if (!predicates.every(E.isRowWise)) return filtered(node, predicates)
|
||||
const split = (canPush: (refs: Set<string>, p: Plan.Expression) => boolean) => {
|
||||
const down: Array<Plan.Expression> = []
|
||||
const here: Array<Plan.Expression> = []
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
/**
|
||||
* Running plans batch by batch over streamed tables.
|
||||
*
|
||||
* Row-wise operations (filters, projections, derived columns without
|
||||
* Row-wise operations (filters, projections and derived columns without
|
||||
* windows, renames, `dropNulls`, `explode`, `unnest`) run on every batch as
|
||||
* it arrives, a slice from the start stops pulling batches once it has its
|
||||
* rows, joins stream their left side against the collected right side, and
|
||||
* concatenations stream their inputs one after the other. Grouping and whole-
|
||||
* table aggregation fold every batch into partial aggregates, so memory grows
|
||||
* with the number of groups, not rows (medians and distinct counts collect
|
||||
* instead). Every other operation collects its inputs first.
|
||||
* with the number of groups, not rows (medians, distinct counts and
|
||||
* aggregates of windows collect instead). Every other operation collects its
|
||||
* inputs first.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
@@ -86,6 +87,7 @@ const collectFrames = (batches: Batches, node: Q.Node): Effect.Effect<F.Frame, D
|
||||
const isRowWise = (node: Q.Node): boolean => {
|
||||
switch (node._tag) {
|
||||
case "Filter":
|
||||
return E.isRowWise(node.predicate)
|
||||
case "Pick":
|
||||
case "Omit":
|
||||
case "Rename":
|
||||
@@ -121,7 +123,9 @@ const aggregate = (
|
||||
const fn: Agg.AggFn = expression.arg === undefined ? "len" : expression.fn
|
||||
return { name, fn, arg: expression.arg }
|
||||
})
|
||||
if (!specs.every((s) => Partial.combinable(s.fn))) return collected(node, catalog)
|
||||
if (!specs.every((s) => Partial.combinable(s.fn) && (s.arg === undefined || E.isRowWise(s.arg)))) {
|
||||
return collected(node, catalog)
|
||||
}
|
||||
const fns = specs.map((s) => s.fn)
|
||||
// The first batch's input vectors and key columns, for result types.
|
||||
let template: { readonly inputs: ReadonlyArray<V.Vector | undefined>; readonly frame: F.Frame } | undefined
|
||||
|
||||
@@ -890,6 +890,24 @@ def extended_cases():
|
||||
add("decimal/sort", "sort by a decimal", D, [{"op": "sort", "keys": [{"expr": col("price"), "descending": True}], "nullsLast": True}])
|
||||
add("decimal/round-ties", "narrowing the scale rounds exact ties", {"left": table([("t", "decimal[6,3]")], {"t": ["0.250", "0.350", "-0.250", "-0.350", "1.050", "2.500", "0.249"]})},
|
||||
[{"op": "select", "exprs": {"one": fn("cast", col("t"), to="decimal[6,1]"), "zero": fn("cast", col("t"), to="decimal[6,0]")}}])
|
||||
# windows see exactly the rows of their input, whatever runs before or after them
|
||||
W = {"left": table([("g", "i32"), ("h", "i32"), ("x", "f64")], {"g": [1, 2, 1, 2], "h": [1, 1, 2, 2], "x": [3.0, 1.0, 2.0, 4.0]}),
|
||||
"right": table([("g", "i32"), ("name", "utf8")], {"g": [1], "name": ["one"]})}
|
||||
add("window/filter-after-sort", "a window predicate sees the sorted rows", W,
|
||||
[{"op": "sort", "keys": [{"expr": col("x")}]}, {"op": "filter", "predicate": fn("gt", fn("cumSum", col("x")), lit(3.0))}])
|
||||
add("window/filter-after-filter", "a window predicate sees only the rows an earlier filter kept", W,
|
||||
[{"op": "filter", "predicate": fn("gt", col("x"), lit(1.0))}, {"op": "filter", "predicate": fn("gt", fn("shift", col("x")), lit(2.0))}])
|
||||
add("window/filter-after-concat", "a window predicate sees every input of a concat", W,
|
||||
[{"op": "concat", "with": "left"}, {"op": "filter", "predicate": fn("gt", fn("cumSum", col("x")), lit(15.0))}])
|
||||
add("window/filter-after-join", "a window predicate sees only the joined rows", W,
|
||||
[{"op": "join", "right": "right", "on": ["g"], "how": "inner"}, {"op": "filter", "predicate": fn("gt", fn("shift", col("x")), lit(2.0))}])
|
||||
add("window/filter-whole", "a window predicate sees the whole input", W,
|
||||
[{"op": "filter", "predicate": fn("gt", fn("cumSum", col("x")), lit(5.0))}])
|
||||
add("window/agg-of-window", "an aggregate of a window sees the whole input", W,
|
||||
[{"op": "agg", "aggs": {"s": agg("sum", fn("cumSum", col("x"))), "n": agg("len")}}])
|
||||
add("window/grouped-agg-of-window", "windows inside grouped aggregates run per group", W,
|
||||
[{"op": "groupBy", "keys": ["g"], "aggs": {"s": agg("sum", fn("cumSum", col("x"))), "l": agg("list", fn("cumSum", col("x"))),
|
||||
"o": agg("sum", over(agg("sum", col("x")), "h"))}}])
|
||||
return out
|
||||
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user