Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-46677][CONNECT][FOLLOWUP] Convert count(df["*"]) to count(1) on client side #44752

Closed

Conversation

zhengruifeng
Copy link
Contributor

@zhengruifeng zhengruifeng commented Jan 16, 2024

What changes were proposed in this pull request?

before #44689, df["*"] and sf.col("*") are both convert to UnresolvedStar, and then Count(UnresolvedStar) is converted to Count(1) in Analyzer:

case f0: UnresolvedFunction if !f0.isDistinct &&
f0.nameParts.map(_.toLowerCase(Locale.ROOT)) == Seq("count") &&
f0.arguments == Seq(UnresolvedStar(None)) =>
// Transform COUNT(*) into COUNT(1).
f0.copy(nameParts = Seq("count"), arguments = Seq(Literal(1)))

in that fix, we introduced a new node UnresolvedDataFrameStar for df["*"] which will be replaced to ResolvedStar later. Unfortunately, it doesn't match Count(UnresolvedStar) any more.
So it causes:

In [1]: from pyspark.sql import functions as sf

In [2]: df1 = spark.createDataFrame([{"id": 1, "val": "v"}])

In [3]: df1.select(sf.count(df1["*"]))
Out[3]: DataFrame[count(id, val): bigint]

which should be

In [3]: df1.select(sf.count(df1["*"]))
Out[3]: DataFrame[count(1): bigint]

In vanilla Spark, it is up to the count function to make such conversion sf.count(df1["*"]) -> sf.count(sf.lit(1)), see

/**
* Aggregate function: returns the number of items in a group.
*
* @group agg_funcs
* @since 1.3.0
*/
def count(e: Column): Column = {
val withoutStar = e.expr match {
// Turn count(*) into count(1)
case _: Star => Column(Literal(1))
case _ => e
}
Column.fn("count", withoutStar)
}

So it is a natural way to fix this behavior on the client side.

Why are the changes needed?

to keep the behavior

Does this PR introduce any user-facing change?

it fix a behavior change introduced in #44689

How was this patch tested?

added ut

Was this patch authored or co-authored using generative AI tooling?

no

@zhengruifeng
Copy link
Contributor Author

thanks, merged to master

@zhengruifeng zhengruifeng deleted the connect_fix_count_df_star branch January 16, 2024 10:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants