This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new dc6e00a2 [SPARK-61600][CONNECT] Take columns in agg, sort, order_by
and the other column-list methods of the Rust API, as select and group_by do
dc6e00a2 is described below
commit dc6e00a27fe93efd25741b2cb692d31e20bf75f3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 09:31:54 2026 +0900
[SPARK-61600][CONNECT] Take columns in agg, sort, order_by and the other
column-list methods of the Rust API, as select and group_by do
### What changes were proposed in this pull request?
In the Rust API, `DataFrame::select` and `group_by` take any columns (`impl
IntoIterator<Item = C>`, `C: Into<Column>`). The other column-list methods took
a `Vec<Expression>`, so the docs and examples wrote `.expression().clone()` for
each column:
```rust
df.group_by([f::col("category")]).agg(vec![
f::sum(f::col("id")).alias("total").expression().clone(),
f::avg(f::col("id")).alias("average").expression().clone(),
])
```
These now take columns, as `select` and `group_by` do:
- `DataFrame`: `sort`, `order_by`, `sort_within_partitions`, `agg`,
`observe`, `observe_with`, `hint_expressions`, `repartition_by_range`,
`repartition_by_range_opt` and `repartition_by_expressions`;
- `GroupedData::agg`;
- `WindowSpec::partition_by` and `Window::partition_by`;
- `WindowSpec::order_by` and `Window::order_by`, which took a
`Vec<SortOrder>`. A column that is a sort order keeps its order, and any other
column is ascending with nulls first, as PySpark's `Window.orderBy` sorts it.
`From<Expression> for Column` and `From<SortOrder> for Column` are added,
so callers that pass a `Vec<Expression>` or a `Vec<SortOrder>` compile as they
are. That includes the Python client, the examples crate and the existing
tests. An empty `vec![]` has no item type to infer and needs
`Vec::<Column>::new()`; `docs/compatibility.md` notes this.
The docs (`dataframes.md`, `examples.md`, `quickstart.md`, `sql.md`) and
the examples drop the `.expression().clone()`, e.g.
`.agg([f::sum(f::col("id")).alias("total"),
f::avg(f::col("id")).alias("average")])` and
`.order_by([f::col("count").desc()])`.
Left as they are:
- the plan-node and expression constructors (`Expression::function`, ...);
- the SQL parameter methods, where a `&str` must not become a column;
- `sample_by`, whose strata are values;
- the `Vec<Column>`/`Vec<&str>` methods (`with_columns`, `drop_columns`,
`grouping_sets`, ...), for a follow-up.
### Why are the changes needed?
The column-list methods were inconsistent, and their docs read badly.
### Does this PR introduce _any_ user-facing change?
Yes, in the Rust API. These methods take any columns: arrays of `Column`,
as well as the `Vec<Expression>` and `Vec<SortOrder>` that they took.
### How was this patch tested?
- New unit tests: each changed method takes `[Column; N]` and a
`Vec<Expression>`, and builds the plan that it built before. A new e2e test
checks `observe_with` of columns and of expressions.
- The lib tests (867 passed), the build of all tests (also with
`wasm-udf`), and the builds of `pyspark-rs` and `examples`.
- The e2e tests of dataframes, columns, functions and the ML estimators
against a Spark 4.3.0 server.
- `check_doc_snippets.py` (56 snippets, 0 failures) and `cargo fmt --all
--check`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #590 from HyukjinKwon/SPARK-61600-column-lists.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/spark-connect/src/column.rs | 55 +++++++
crates/spark-connect/src/dataframe.rs | 243 ++++++++++++++++++++++++----
crates/spark-connect/src/group.rs | 38 ++++-
crates/spark-connect/src/window.rs | 68 ++++++--
crates/spark-connect/tests/e2e_columns.rs | 3 +-
crates/spark-connect/tests/e2e_dataframe.rs | 49 ++++++
docs/compatibility.md | 11 ++
docs/dataframes.md | 14 +-
docs/examples.md | 7 +-
docs/quickstart.md | 6 +-
docs/sql.md | 2 +-
examples/src/databricks.rs | 7 +-
examples/src/reader.rs | 2 +-
13 files changed, 438 insertions(+), 67 deletions(-)
diff --git a/crates/spark-connect/src/column.rs
b/crates/spark-connect/src/column.rs
index 94f647a0..d16c167e 100644
--- a/crates/spark-connect/src/column.rs
+++ b/crates/spark-connect/src/column.rs
@@ -659,6 +659,35 @@ impl From<&String> for Column {
}
}
+// An expression is accepted anywhere a `Column` is, as the Column of it, so
the APIs of
+// `impl IntoIterator<Item = impl Into<Column>>` take the `Vec<Expression>`
that some of them
+// took before, such as `df.sort(vec![col("x").expression().clone()])`.
+impl From<Expression> for Column {
+ fn from(expr: Expression) -> Column {
+ Column::new(expr)
+ }
+}
+
+// A sort order is accepted as the Column of it that `asc` and `desc` make, so
+// `WindowSpec::order_by` takes the `Vec<SortOrder>` that it took before.
+impl From<SortOrder> for Column {
+ fn from(sort: SortOrder) -> Column {
+ Column {
+ expr: ExpressionNode::SortOrder(Box::new(sort)).into(),
+ }
+ }
+}
+
+/// The expressions of `columns`, as the plans of the APIs that take Columns
hold them.
+pub(crate) fn expressions_of<C: Into<Column>>(
+ columns: impl IntoIterator<Item = C>,
+) -> Vec<Expression> {
+ columns
+ .into_iter()
+ .map(|column| column.into().expr)
+ .collect()
+}
+
/// Mirrors `pyspark.sql.functions.lit` for an integer value.
///
/// PySpark infers `IntegerType` for a Python int that fits in i32 and
`LongType`
@@ -949,6 +978,32 @@ mod tests {
assert!(matches!(c3.expr.node(), ExpressionNode::ColumnReference(_)));
}
+ #[test]
+ fn expressions_and_sort_orders_are_the_columns_of_them() {
+ // An expression is the Column of it, which shares its node.
+ let expression = (col("x") + lit(1)).expression().clone();
+ let column = Column::from(expression.clone());
+ assert_eq!(column, Column::new(expression.clone()));
+ assert!(std::ptr::eq(column.expression().node(), expression.node()));
+ // A sort order is the Column of it that `asc` and `desc` make.
+ let sort = SortOrder::desc_nulls_first(col("x").expression().clone());
+ assert_eq!(Column::from(sort), col("x").desc_nulls_first());
+ // The expressions that the APIs of columns take, of Columns, names
and expressions
+ // alike, in their order.
+ assert_eq!(
+ expressions_of([col("a"), col("b").desc()]),
+ vec![
+ col("a").expression().clone(),
+ col("b").desc().expression().clone()
+ ]
+ );
+ assert_eq!(
+ expressions_of(["a", "b"]),
+ expressions_of(vec![Expression::column("a"),
Expression::column("b")])
+ );
+ assert!(expressions_of(Vec::<Column>::new()).is_empty());
+ }
+
#[test]
fn test_lit_functions() {
// Test lit with small number (fits in i32)
diff --git a/crates/spark-connect/src/dataframe.rs
b/crates/spark-connect/src/dataframe.rs
index a4c4c835..eb5fc8b9 100644
--- a/crates/spark-connect/src/dataframe.rs
+++ b/crates/spark-connect/src/dataframe.rs
@@ -10,7 +10,7 @@ use spark_connect_core::error::{Result, SparkError,
SparkErrorKind};
use spark_connect_core::runtime::{block_on, get_runtime};
use spark_connect_proto as proto;
-use crate::column::Column;
+use crate::column::{expressions_of, Column};
use crate::expression::{Expression, ExpressionNode, SortOrder};
use crate::plan::{
AggregateGroupType, AsOfJoinDirection, AsOfJoinType, JoinType,
LogicalPlan, RelationOwner,
@@ -600,18 +600,20 @@ impl DataFrame {
self.with_cached_schema(plan)
}
- /// Sort rows.
- pub fn sort(&self, columns: Vec<Expression>) -> DataFrame {
+ /// Sort rows by `columns`. A sort order, of [`Column::asc`],
[`Column::desc`] and their
+ /// nulls variants, sorts as it says; any other column is sorted
ascending, nulls first,
+ /// as PySpark's `sort` sorts it.
+ pub fn sort<C: Into<Column>>(&self, columns: impl IntoIterator<Item = C>)
-> DataFrame {
let plan = LogicalPlan::Sort {
input: Arc::clone(&self.plan),
- order: columns,
+ order: expressions_of(columns),
is_global: true,
};
self.with_cached_schema(plan)
}
/// Alias for sort().
- pub fn order_by(&self, columns: Vec<Expression>) -> DataFrame {
+ pub fn order_by<C: Into<Column>>(&self, columns: impl IntoIterator<Item =
C>) -> DataFrame {
self.sort(columns)
}
@@ -809,20 +811,25 @@ impl DataFrame {
name: &str,
parameters: impl IntoIterator<Item = S>,
) -> DataFrame {
- let parameters = parameters
+ let parameters: Vec<Expression> = parameters
.into_iter()
.map(|p| crate::plan::hint_parameter(&p.into()))
.collect();
self.hint_expressions(name, parameters)
}
- /// Specify a hint of parameters given as expressions, mirroring
`pyspark.sql.DataFrame.hint`,
- /// which sends `lit` of each parameter: a literal, or a Column.
- pub fn hint_expressions(&self, name: &str, parameters: Vec<Expression>) ->
DataFrame {
+ /// Specify a hint of parameters given as Columns, mirroring
`pyspark.sql.DataFrame.hint`,
+ /// which sends `lit` of each parameter: a literal, or a Column. A name is
the column of that
+ /// name, as everywhere a Column is taken: [`DataFrame::hint`] sends
strings as literals.
+ pub fn hint_expressions<C: Into<Column>>(
+ &self,
+ name: &str,
+ parameters: impl IntoIterator<Item = C>,
+ ) -> DataFrame {
let plan = LogicalPlan::Hint {
input: Arc::clone(&self.plan),
name: name.to_string(),
- parameters,
+ parameters: expressions_of(parameters),
};
self.with_cached_schema(plan)
}
@@ -1803,10 +1810,10 @@ impl DataFrame {
/// Mirrors `DataFrame.repartitionByRange(numPartitions, *cols)`: as
PySpark's, a count that
/// is not positive is a `VALUE_NOT_POSITIVE` error, and no columns a
`CANNOT_BE_EMPTY` one
/// (the server would split the rows round-robin instead).
- pub fn repartition_by_range(
+ pub fn repartition_by_range<C: Into<Column>>(
&self,
num_partitions: i32,
- columns: Vec<Expression>,
+ columns: impl IntoIterator<Item = C>,
) -> Result<DataFrame> {
self.repartition_by_range_opt(Some(num_partitions), columns)
}
@@ -1815,10 +1822,10 @@ impl DataFrame {
/// sends no count, so the server picks it. Mirrors
`DataFrame.repartitionByRange(col)`
/// and `repartitionByRange(col, *cols)`, which PySpark sends with
`numPartitions=None`.
/// The errors are those of [`DataFrame::repartition_by_range`].
- pub fn repartition_by_range_opt(
+ pub fn repartition_by_range_opt<C: Into<Column>>(
&self,
num_partitions: Option<i32>,
- columns: Vec<Expression>,
+ columns: impl IntoIterator<Item = C>,
) -> Result<DataFrame> {
if let Some(n) = num_partitions.filter(|n| *n <= 0) {
return Err(SparkError::classed(
@@ -1827,6 +1834,7 @@ impl DataFrame {
&[("arg_name", "numPartitions"), ("arg_value",
&n.to_string())],
));
}
+ let columns = expressions_of(columns);
if columns.is_empty() {
return Err(SparkError::classed(
SparkErrorKind::ValueError,
@@ -1856,15 +1864,15 @@ impl DataFrame {
/// Repartition into `num_partitions` by hashing the given column
expressions.
/// Mirrors `df.repartition(numPartitions, *cols)`.
- pub fn repartition_by_expressions(
+ pub fn repartition_by_expressions<C: Into<Column>>(
&self,
num_partitions: i32,
- columns: Vec<Expression>,
+ columns: impl IntoIterator<Item = C>,
) -> DataFrame {
let plan = LogicalPlan::RepartitionByExpression {
input: Arc::clone(&self.plan),
num_partitions,
- expressions: columns,
+ expressions: expressions_of(columns),
};
self.with_cached_schema(plan)
}
@@ -1918,11 +1926,15 @@ impl DataFrame {
/// Observe metrics on this DataFrame. With no `exprs`, the action fails
on the server, where
/// PySpark's `observe` raises `CANNOT_BE_EMPTY` at the call, as
/// [`DataFrame::observe_with`] does.
- pub fn observe(&self, name: &str, exprs: Vec<Expression>) -> DataFrame {
+ pub fn observe<C: Into<Column>>(
+ &self,
+ name: &str,
+ exprs: impl IntoIterator<Item = C>,
+ ) -> DataFrame {
let plan = LogicalPlan::Observe {
input: Arc::clone(&self.plan),
name: name.to_string(),
- exprs,
+ exprs: expressions_of(exprs),
observation: None,
};
self.with_cached_schema(plan)
@@ -1934,11 +1946,12 @@ impl DataFrame {
/// whose metrics each action that runs the DataFrame sets in the
observation.
/// `REUSE_OBSERVATION` for an observation used already, and
`UNSUPPORTED_OPERATION` for a
/// streaming DataFrame.
- pub fn observe_with(
+ pub fn observe_with<C: Into<Column>>(
&self,
observation: &crate::observation::Observation,
- exprs: Vec<Expression>,
+ exprs: impl IntoIterator<Item = C>,
) -> Result<DataFrame> {
+ let exprs = expressions_of(exprs);
// As PySpark's `observe`, which checks this first.
if exprs.is_empty() {
return Err(SparkError::classed(
@@ -1992,12 +2005,12 @@ impl DataFrame {
/// Perform aggregation without grouping. With no `expressions`, the
result is one row of
/// no columns, as of the Scala client's `agg(Map.empty)`, where PySpark's
`agg` raises
/// `CANNOT_BE_EMPTY`.
- pub fn agg(&self, expressions: Vec<Expression>) -> DataFrame {
+ pub fn agg<C: Into<Column>>(&self, expressions: impl IntoIterator<Item =
C>) -> DataFrame {
let plan = LogicalPlan::Aggregate {
input: Arc::clone(&self.plan),
group_type: AggregateGroupType::GroupBy,
grouping_expressions: vec![],
- aggregate_expressions: expressions,
+ aggregate_expressions: expressions_of(expressions),
pivot_col: None,
pivot_values: vec![],
grouping_sets: vec![],
@@ -2282,11 +2295,14 @@ impl DataFrame {
crate::group::GroupedData::new_grouping_sets_of(self.clone(),
grouping_sets, group_cols)
}
- /// Sort within partitions (local sort).
- pub fn sort_within_partitions(&self, columns: Vec<Expression>) ->
DataFrame {
+ /// Sort within partitions (local sort), by `columns` as
[`DataFrame::sort`] sorts by them.
+ pub fn sort_within_partitions<C: Into<Column>>(
+ &self,
+ columns: impl IntoIterator<Item = C>,
+ ) -> DataFrame {
let plan = LogicalPlan::Sort {
input: Arc::clone(&self.plan),
- order: columns,
+ order: expressions_of(columns),
is_global: false,
};
self.with_cached_schema(plan)
@@ -5310,7 +5326,7 @@ mod plan_construction_tests {
let Err(error) = session()
.range(3)
.unwrap()
- .observe_with(&observation, vec![])
+ .observe_with(&observation, Vec::<Column>::new())
else {
panic!("no exprs must be rejected");
};
@@ -5321,6 +5337,24 @@ mod plan_construction_tests {
);
}
+ /// `observe_with` takes Columns, as `observe` does, and the
`Vec<Expression>` that it took
+ /// before: no expressions of either, or of an iterator, are
`CANNOT_BE_EMPTY`.
+ #[test]
+ fn observe_with_takes_columns_and_expressions_alike() {
+ let df = session().range(3).unwrap();
+ let observation = crate::observation::Observation::new("metrics");
+ for result in [
+ df.observe_with(&observation, [] as [Column; 0]),
+ df.observe_with(&observation, Vec::<Expression>::new()),
+ df.observe_with(&observation, std::iter::empty::<&str>()),
+ ] {
+ let Err(error) = result else {
+ panic!("no exprs must be rejected");
+ };
+ assert_eq!(error.get_condition().as_deref(),
Some("CANNOT_BE_EMPTY"));
+ }
+ }
+
fn session() -> SparkSession {
SparkSession::builder()
.remote("sc://localhost:15002")
@@ -6349,6 +6383,51 @@ mod plan_construction_tests {
}
}
+ /// Both range repartitions take Columns, as `select` does, and the
`Vec<Expression>` that
+ /// they took before, of which they build the plan that they built of the
expressions.
+ #[test]
+ fn repartition_by_range_takes_columns_and_expressions_alike() {
+ use crate::functions::col;
+
+ let df = session().range(5).unwrap();
+ let columns = || [col("id"), col("id").desc_nulls_last()];
+ let expressions = || {
+ vec![
+ col("id").expression().clone(),
+ col("id").desc_nulls_last().expression().clone(),
+ ]
+ };
+ let before = |num_partitions| {
+ LogicalPlan::RepartitionByRange {
+ input: Arc::clone(&df.plan),
+ num_partitions,
+ partition_exprs: vec![
+ col("id").asc_nulls_first().expression().clone(),
+ col("id").desc_nulls_last().expression().clone(),
+ ],
+ }
+ .to_proto()
+ };
+ for (num_partitions, of_columns, of_expressions) in [
+ (
+ Some(3),
+ df.repartition_by_range(3, columns()),
+ df.repartition_by_range(3, expressions()),
+ ),
+ (
+ None,
+ df.repartition_by_range_opt(None, columns()),
+ df.repartition_by_range_opt(None, expressions()),
+ ),
+ ] {
+ assert_eq!(of_columns.unwrap().plan.to_proto(),
before(num_partitions));
+ assert_eq!(
+ of_expressions.unwrap().plan.to_proto(),
+ before(num_partitions)
+ );
+ }
+ }
+
/// As PySpark's `repartitionByRange(numPartitions, *cols)`: a count that
is not positive,
/// then no columns, are errors, where the server would split the rows
round-robin.
#[test]
@@ -6359,8 +6438,8 @@ mod plan_construction_tests {
let id = || vec![col("id").expression().clone()];
let error = |result: Result<DataFrame>| result.err().expect("an
error");
for empty in [
- error(df.repartition_by_range(2, vec![])),
- error(df.repartition_by_range_opt(None, vec![])),
+ error(df.repartition_by_range(2, Vec::<Column>::new())),
+ error(df.repartition_by_range_opt(None, Vec::<Column>::new())),
] {
assert_eq!(empty.kind, SparkErrorKind::ValueError);
assert_eq!(empty.get_condition().as_deref(),
Some("CANNOT_BE_EMPTY"));
@@ -6372,7 +6451,7 @@ mod plan_construction_tests {
for n in [0, -1] {
for result in [
df.repartition_by_range(n, id()),
- df.repartition_by_range(n, vec![]),
+ df.repartition_by_range(n, Vec::<Column>::new()),
] {
let not_positive = error(result);
assert_eq!(
@@ -6461,6 +6540,110 @@ mod plan_construction_tests {
ser(&df.stat().freq_items(vec!["id"], 0.5));
}
+ /// The methods of lists of columns take Columns, as `select` does, and the
+ /// `Vec<Expression>` that they took before, of which they build the plans
that they built
+ /// of the expressions.
+ #[test]
+ fn column_list_methods_take_columns_and_expressions_alike() {
+ use crate::column::lit;
+ use crate::functions::{col, count, sum};
+
+ let df = session().range(5).unwrap();
+ let input = || Arc::clone(&df.plan);
+ let order = || [col("id").desc(), col("id")];
+ let order_expressions = || {
+ vec![
+ col("id").desc().expression().clone(),
+ col("id").expression().clone(),
+ ]
+ };
+ let metrics = || [sum(col("id")).alias("total"), count(lit(1))];
+ let metric_expressions = || {
+ vec![
+ sum(col("id")).alias("total").expression().clone(),
+ count(lit(1)).expression().clone(),
+ ]
+ };
+ let parameters = || [lit(3), col("id")];
+ let parameter_expressions =
+ || vec![lit(3).expression().clone(),
col("id").expression().clone()];
+ let keys = || [col("id"), col("id") % lit(2)];
+ let key_expressions = || {
+ vec![
+ col("id").expression().clone(),
+ (col("id") % lit(2)).expression().clone(),
+ ]
+ };
+ let sorted = |is_global| LogicalPlan::Sort {
+ input: input(),
+ order: order_expressions(),
+ is_global,
+ };
+ let cases = [
+ (sorted(true), df.sort(order()), df.sort(order_expressions())),
+ (
+ sorted(true),
+ df.order_by(order()),
+ df.order_by(order_expressions()),
+ ),
+ (
+ sorted(false),
+ df.sort_within_partitions(order()),
+ df.sort_within_partitions(order_expressions()),
+ ),
+ (
+ LogicalPlan::Aggregate {
+ input: input(),
+ group_type: AggregateGroupType::GroupBy,
+ grouping_expressions: vec![],
+ aggregate_expressions: metric_expressions(),
+ pivot_col: None,
+ pivot_values: vec![],
+ grouping_sets: vec![],
+ },
+ df.agg(metrics()),
+ df.agg(metric_expressions()),
+ ),
+ (
+ LogicalPlan::Observe {
+ input: input(),
+ name: "metrics".to_string(),
+ exprs: metric_expressions(),
+ observation: None,
+ },
+ df.observe("metrics", metrics()),
+ df.observe("metrics", metric_expressions()),
+ ),
+ (
+ LogicalPlan::Hint {
+ input: input(),
+ name: "rebalance".to_string(),
+ parameters: parameter_expressions(),
+ },
+ df.hint_expressions("rebalance", parameters()),
+ df.hint_expressions("rebalance", parameter_expressions()),
+ ),
+ (
+ LogicalPlan::RepartitionByExpression {
+ input: input(),
+ num_partitions: 3,
+ expressions: key_expressions(),
+ },
+ df.repartition_by_expressions(3, keys()),
+ df.repartition_by_expressions(3, key_expressions()),
+ ),
+ ];
+ for (before, of_columns, of_expressions) in &cases {
+ assert_eq!(of_columns.plan.to_proto(), before.to_proto());
+ assert_eq!(of_expressions.plan.to_proto(), before.to_proto());
+ }
+ // A name is the column of it, as in `select`.
+ assert_eq!(
+ df.sort(["id"]).plan.to_proto(),
+ df.sort([col("id")]).plan.to_proto()
+ );
+ }
+
/// Streaming reader terminal builders (serialize their plans) + the
writer builder
/// chain across every Trigger variant (setters only; no server-side
start()).
#[test]
diff --git a/crates/spark-connect/src/group.rs
b/crates/spark-connect/src/group.rs
index 6dea5421..4ea7f20e 100644
--- a/crates/spark-connect/src/group.rs
+++ b/crates/spark-connect/src/group.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use spark_connect_core::error::{Result, SparkError, SparkErrorKind};
-use crate::column::Column;
+use crate::column::{expressions_of, Column};
use crate::dataframe::DataFrame;
use crate::expression::Expression;
use crate::plan::{AggregateGroupType, LogicalPlan};
@@ -412,7 +412,7 @@ impl GroupedData {
/// Perform an aggregation. With no `expressions`, the result is the
distinct grouping keys,
/// as of the Scala client, where PySpark's `agg` raises an
`AssertionError`.
- pub fn agg(&self, expressions: Vec<Expression>) -> DataFrame {
+ pub fn agg<C: Into<Column>>(&self, expressions: impl IntoIterator<Item =
C>) -> DataFrame {
// Convert group columns to expressions
let grouping_expressions = self
.group_cols
@@ -431,7 +431,7 @@ impl GroupedData {
input: Arc::clone(&self.dataframe.plan),
group_type: self.group_type,
grouping_expressions,
- aggregate_expressions: expressions,
+ aggregate_expressions: expressions_of(expressions),
pivot_col: self.pivot_col.clone(),
pivot_values: self.pivot_values.clone(),
grouping_sets,
@@ -485,7 +485,7 @@ impl GroupedData {
}
columns.iter().map(|column| column.to_string()).collect()
};
- let expressions = names
+ let expressions: Vec<Expression> = names
.iter()
.map(|name| {
Expression::function(
@@ -1113,6 +1113,36 @@ mod tests {
}
}
+ /// `agg` takes Columns, as `DataFrame::group_by` does, and the
`Vec<Expression>` that it
+ /// took before, of which it builds the plan that it built of the
expressions.
+ #[test]
+ fn group_agg_takes_columns_and_expressions_alike() {
+ use crate::column::col;
+ use crate::functions::{max, sum};
+
+ let df = session().range(10).unwrap();
+ let grouped = df.group_by(["id"]);
+ let expressions = || {
+ vec![
+ sum(col("id")).alias("total").expression().clone(),
+ max(col("id")).expression().clone(),
+ ]
+ };
+ let before = LogicalPlan::Aggregate {
+ input: Arc::clone(&df.plan),
+ group_type: AggregateGroupType::GroupBy,
+ grouping_expressions: vec![col("id").expression().clone()],
+ aggregate_expressions: expressions(),
+ pivot_col: None,
+ pivot_values: vec![],
+ grouping_sets: vec![],
+ }
+ .to_proto();
+ let of_columns = grouped.agg([sum(col("id")).alias("total"),
max(col("id"))]);
+ assert_eq!(of_columns.plan.to_proto(), before);
+ assert_eq!(grouped.agg(expressions()).plan.to_proto(), before);
+ }
+
#[test]
fn pivot_plan() {
let spark = session();
diff --git a/crates/spark-connect/src/window.rs
b/crates/spark-connect/src/window.rs
index 901a9e4b..32536792 100644
--- a/crates/spark-connect/src/window.rs
+++ b/crates/spark-connect/src/window.rs
@@ -3,7 +3,8 @@
//! Provides the `Window` static builder and `WindowSpec` for defining window
partitions,
//! ordering, and frame boundaries used with `Column.over()`.
-use crate::expression::{Expression, SortOrder};
+use crate::column::{expressions_of, Column};
+use crate::expression::{Expression, ExpressionNode, SortOrder};
/// Frame bound value used in window frame definitions.
#[derive(Debug, Clone, PartialEq)]
@@ -74,14 +75,23 @@ impl WindowSpec {
}
/// Add partition columns to this window specification.
- pub fn partition_by(mut self, cols: Vec<Expression>) -> Self {
- self.partition_spec.extend(cols);
+ pub fn partition_by<C: Into<Column>>(mut self, cols: impl
IntoIterator<Item = C>) -> Self {
+ self.partition_spec.extend(expressions_of(cols));
self
}
- /// Set ordering for this window specification.
- pub fn order_by(mut self, sorts: Vec<SortOrder>) -> Self {
- self.order_spec.extend(sorts);
+ /// Set ordering for this window specification. A sort order, of
[`Column::asc`],
+ /// [`Column::desc`] and their nulls variants, or a [`SortOrder`], sorts
as it says; any
+ /// other column is sorted ascending, nulls first, as PySpark's
`WindowSpec.orderBy` sorts it.
+ pub fn order_by<C: Into<Column>>(mut self, cols: impl IntoIterator<Item =
C>) -> Self {
+ self.order_spec.extend(
+ expressions_of(cols)
+ .into_iter()
+ .map(|expr| match expr.node() {
+ ExpressionNode::SortOrder(sort) => (**sort).clone(),
+ _ => SortOrder::asc_nulls_first(expr),
+ }),
+ );
self
}
@@ -126,13 +136,13 @@ impl Window {
}
/// Create a WindowSpec partitioned by the given columns.
- pub fn partition_by(cols: Vec<Expression>) -> WindowSpec {
+ pub fn partition_by<C: Into<Column>>(cols: impl IntoIterator<Item = C>) ->
WindowSpec {
WindowSpec::new().partition_by(cols)
}
- /// Create a WindowSpec ordered by the given sort orders.
- pub fn order_by(sorts: Vec<SortOrder>) -> WindowSpec {
- WindowSpec::new().order_by(sorts)
+ /// Create a WindowSpec ordered by the given columns, as
[`WindowSpec::order_by`] orders it.
+ pub fn order_by<C: Into<Column>>(cols: impl IntoIterator<Item = C>) ->
WindowSpec {
+ WindowSpec::new().order_by(cols)
}
/// Create a WindowSpec with a ROWS frame between the given bounds.
@@ -243,6 +253,44 @@ mod tests {
);
}
+ /// `partition_by` and `order_by` take Columns, as `DataFrame::select`
does, and the
+ /// `Vec<Expression>` and `Vec<SortOrder>` that they took before, which
they keep as they
+ /// kept them. A Column of `order_by` that is not a sort order is
ascending, nulls first,
+ /// as PySpark's `WindowSpec.orderBy` sorts it.
+ #[test]
+ fn spec_builders_take_columns_and_expressions_alike() {
+ use crate::column::col as column;
+
+ let before = WindowSpec {
+ partition_spec: vec![col("a"), col("b")],
+ order_spec: vec![SortOrder::desc_nulls_last(col("c")), sort("d")],
+ frame_spec: None,
+ };
+ let of_columns = || {
+ WindowSpec::new()
+ .partition_by([column("a"), column("b")])
+ .order_by([column("c").desc(), column("d")])
+ };
+ assert_eq!(of_columns(), before);
+ assert_eq!(
+ WindowSpec::new()
+ .partition_by(vec![col("a"), col("b")])
+ .order_by(vec![SortOrder::desc_nulls_last(col("c")),
sort("d")]),
+ before
+ );
+ assert_eq!(
+ Window::partition_by(["a", "b"]).order_by([column("c").desc(),
column("d")]),
+ before
+ );
+ assert_eq!(
+ Window::order_by([column("c").desc(),
column("d")]).partition_by(["a", "b"]),
+ before
+ );
+ // And so are the window expressions over them.
+ let over = |spec|
crate::functions::sum(column("x")).over(spec).to_proto();
+ assert_eq!(over(of_columns()), over(before));
+ }
+
#[test]
fn frame_boundaries_are_sent_as_pyspark_sends_them() {
use spark_connect_proto::expression::literal::LiteralType;
diff --git a/crates/spark-connect/tests/e2e_columns.rs
b/crates/spark-connect/tests/e2e_columns.rs
index a0e0a5d1..b4d2bfb6 100644
--- a/crates/spark-connect/tests/e2e_columns.rs
+++ b/crates/spark-connect/tests/e2e_columns.rs
@@ -219,7 +219,8 @@ fn column_membership_conditional_window() {
let _ = one(&df, lit_double(1.5));
let _ = one(&df, lit_boolean(true));
// sort-order builders + window (over)
- let w =
Window::partition_by(vec![col("id").expression().clone()]).order_by(vec![]);
+ let w =
+
Window::partition_by(vec![col("id").expression().clone()]).order_by(Vec::<Column>::new());
let _ = one(&df, f::sum(col("val")).over(w));
// asc/desc builders exercised through order_by
let _ = df
diff --git a/crates/spark-connect/tests/e2e_dataframe.rs
b/crates/spark-connect/tests/e2e_dataframe.rs
index 82633a96..dbdb10d3 100644
--- a/crates/spark-connect/tests/e2e_dataframe.rs
+++ b/crates/spark-connect/tests/e2e_dataframe.rs
@@ -362,6 +362,55 @@ fn dataframe_metadata_json_semantics() {
assert_eq!(parts.len(), 2);
}
+/// `observe_with` takes Columns, as `select` does, and the `Vec<Expression>`
that it took
+/// before: an action sets the same metrics of both in their observations.
+#[test]
+fn observe_with_takes_columns_and_expressions_alike() {
+ if !should_run() {
+ return;
+ }
+ use spark_connect::observation::Observation;
+ use spark_connect_proto::expression::literal::LiteralType;
+
+ let df = df4(&session());
+ let of_columns = Observation::new("of_columns");
+ let of_expressions = Observation::new("of_expressions");
+ df.observe_with(
+ &of_columns,
+ [
+ f::count(lit(1)).alias("rows"),
+ f::max(col("id")).alias("top"),
+ ],
+ )
+ .unwrap()
+ .collect()
+ .unwrap();
+ df.observe_with(
+ &of_expressions,
+ vec![
+ f::count(lit(1)).alias("rows").expression().clone(),
+ f::max(col("id")).alias("top").expression().clone(),
+ ],
+ )
+ .unwrap()
+ .collect()
+ .unwrap();
+ let metrics = |observation: &Observation| -> Vec<(String,
Option<LiteralType>)> {
+ observation
+ .get()
+ .unwrap()
+ .into_iter()
+ .map(|(key, value)| (key, value.literal_type))
+ .collect()
+ };
+ let expected = vec![
+ ("rows".to_string(), Some(LiteralType::Long(4))),
+ ("top".to_string(), Some(LiteralType::Integer(3))),
+ ];
+ assert_eq!(metrics(&of_columns), expected);
+ assert_eq!(metrics(&of_expressions), expected);
+}
+
/// `GroupedData.pivot` takes explicit values of the types of the Spark
literals, dates,
/// timestamps and decimals too: they give the columns of the pivot without
values, which PySpark
/// computes for the same data. PySpark itself rejects those types as values
(NOT_EXPECTED_TYPE),
diff --git a/docs/compatibility.md b/docs/compatibility.md
index da62d679..b9b9c065 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -20,6 +20,17 @@ microseconds. Downstream exhaustive matches on these public
enums must handle
the new variant. Rust interval map keys are stringified as raw microseconds;
Python `timedelta` map keys are not yet supported.
+`DataFrame::sort`, `order_by`, `sort_within_partitions`, `agg`, `observe`,
`observe_with`,
+`hint_expressions`, `repartition_by_range`, `repartition_by_range_opt` and
+`repartition_by_expressions`, `GroupedData::agg`, and the `partition_by` and
`order_by` of
+`Window` and `WindowSpec` take `impl IntoIterator<Item = impl Into<Column>>`,
as `select` and
+`group_by` do: Columns, column names or expressions, such as
`df.sort([col("x").desc()])` and
+`.agg([sum(col("id")).alias("total")])`, without `.expression().clone()`. The
`Vec<Expression>`
+that they took still compiles, by the new `From<Expression> for Column`, and
so does the
+`Vec<SortOrder>` of the `order_by` of a window, by `From<SortOrder> for
Column`; there a Column
+that is not a sort order is sorted ascending, nulls first, as PySpark's
`WindowSpec.orderBy`
+sorts it. An empty `vec![]` has no item type to infer: pass
`Vec::<Column>::new()` instead.
+
`BinaryClassificationEvaluator::set_score_col` and `score_col`, and the Python
`scoreCol=` argument and `setScoreCol` of v4.2.0 are removed, without an alias:
Spark's evaluator has no `scoreCol` param, so no value of it worked on the
server.
diff --git a/docs/dataframes.md b/docs/dataframes.md
index 73bf1756..2509e75b 100644
--- a/docs/dataframes.md
+++ b/docs/dataframes.md
@@ -53,7 +53,7 @@ let df = df.drop(vec!["temp_col"]);
let df = df.distinct();
// Sort
-let df = df.order_by(vec![f::col("id").expression().clone()]);
+let df = df.order_by([f::col("id")]);
// Limit
let df = df.limit(5);
@@ -68,14 +68,14 @@ use spark_connect::{functions as f, lit};
// Group by one column
let agg_df = df.group_by([f::col("category")])
- .agg(vec![f::count(lit(1)).expression().clone()]);
+ .agg([f::count(lit(1))]);
// Group by multiple columns with multiple aggregates
let agg_df = df.group_by([f::col("category"), f::col("year")])
- .agg(vec![
- f::sum(f::col("amount")).expression().clone(),
- f::avg(f::col("value")).expression().clone(),
- f::min(f::col("price")).alias("min_price").expression().clone(),
+ .agg([
+ f::sum(f::col("amount")),
+ f::avg(f::col("value")),
+ f::min(f::col("price")).alias("min_price"),
]);
```
@@ -145,7 +145,7 @@ let result = spark.range(101)?
.with_column("squared", f::col("id") * f::col("id"))
.filter(f::col("squared").gt(lit(100)))
.select([f::col("id"), f::col("squared")])
- .order_by(vec![f::col("id").expression().clone()])
+ .order_by([f::col("id")])
.limit(10);
result.show(10)?;
```
diff --git a/docs/examples.md b/docs/examples.md
index 1603432a..7ab21ca0 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -17,10 +17,7 @@ let df = spark.read()
df
.group_by([f::col("category")])
- .agg(vec![
- f::sum(f::col("amount")).expression().clone(),
- f::avg(f::col("price")).expression().clone(),
- ])
+ .agg([f::sum(f::col("amount")), f::avg(f::col("price"))])
.show(20)?;
```
@@ -40,7 +37,7 @@ df
f::split(f::col("line"), lit_string(" "))
).alias("word")])
.group_by([f::col("word")])
- .agg(vec![f::count(f::col("word")).expression().clone()])
+ .agg([f::count(f::col("word"))])
.show(20)?;
```
diff --git a/docs/quickstart.md b/docs/quickstart.md
index bc39d25a..659e8c48 100644
--- a/docs/quickstart.md
+++ b/docs/quickstart.md
@@ -57,9 +57,9 @@ let df = spark.range(20)?;
df
.with_column("category", f::col("id") % lit(3))
.group_by([f::col("category")])
- .agg(vec![
- f::sum(f::col("id")).alias("total").expression().clone(),
- f::avg(f::col("id")).alias("average").expression().clone(),
+ .agg([
+ f::sum(f::col("id")).alias("total"),
+ f::avg(f::col("id")).alias("average"),
])
.show(20)?;
```
diff --git a/docs/sql.md b/docs/sql.md
index c8be9a2b..63e4114f 100644
--- a/docs/sql.md
+++ b/docs/sql.md
@@ -150,7 +150,7 @@ by_cat.create_or_replace_temp_view("category_stats")?;
// DataFrame API: filter and order
let result = spark.sql("SELECT * FROM category_stats")?
.filter(f::col("avg_price").gt(lit(50)))
- .order_by(vec![f::col("count").desc().expression().clone()]);
+ .order_by([f::col("count").desc()]);
result.show(10)?;
```
diff --git a/examples/src/databricks.rs b/examples/src/databricks.rs
index 0620814f..4f706113 100644
--- a/examples/src/databricks.rs
+++ b/examples/src/databricks.rs
@@ -47,11 +47,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let grouped = df.group_by([col("pickup_zip")]);
// average the fare amount and order by the top 10 zip codes
- let df = grouped.agg(vec![avg(col("fare_amount"))
- .alias("avg_fare_amount")
- .expression()
- .clone()]);
- let df = df.sort(vec![col("avg_fare_amount").desc().expression().clone()]);
+ let df = grouped.agg([avg(col("fare_amount")).alias("avg_fare_amount")]);
+ let df = df.sort([col("avg_fare_amount").desc()]);
let df = df.limit(10);
df.show(10)?;
diff --git a/examples/src/reader.rs b/examples/src/reader.rs
index 5707e411..3474d7eb 100644
--- a/examples/src/reader.rs
+++ b/examples/src/reader.rs
@@ -42,7 +42,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
(lit_double(3.0) + F::col("age_int")).alias("addition"),
]);
- let df = df.sort(vec![F::col("name").desc().expression().clone()]);
+ let df = df.sort([F::col("name").desc()]);
df.show(5)?;
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]