You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/11/01 02:12:56 UTC

[GitHub] [spark] amaliujia commented on a diff in pull request #38395: [SPARK-40917][SQL] Add a dedicated logical plan for `Summary`

amaliujia commented on code in PR #38395:
URL: https://github.com/apache/spark/pull/38395#discussion_r1010010032


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -2101,3 +2101,53 @@ object AsOfJoin {
     }
   }
 }
+
+
+/**
+ * A logical plan for summary.
+ */
+case class UnresolvedSummary(
+    child: LogicalPlan,
+    statistics: Seq[String]) extends UnaryNode {
+
+  private lazy val supported =
+    Set("count", "count_distinct", "approx_count_distinct", "mean", "stddev", "min", "max")
+
+  {
+    // TODO: throw AnalysisException instead
+    require(statistics.nonEmpty)

Review Comment:
   I am thinking this is easy to handle in this PR:
   
   either we return the plan in `ResolveStatsFunctions` when we find `UnresolvedSummary` has empty `statistics`, or we through the exception in `ResolveStatsFunctions` when seeing empty `statistics`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveStatsFunctions.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate._
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.SUMMARY
+import org.apache.spark.sql.types._
+
+/**
+ * Resolve StatsFunctions.
+ */
+object ResolveStatsFunctions extends Rule[LogicalPlan] {
+  def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsWithPruning(
+    _.containsPattern(SUMMARY), ruleId) {
+
+    case s @ UnresolvedSummary(child, statistics) if s.childrenResolved =>
+      val percentiles = statistics.filter(p => p.endsWith("%"))
+        .map(p => p.stripSuffix("%").toDouble / 100.0)
+
+      var mapExprs = Seq.empty[NamedExpression]
+      child.output.foreach { attr =>
+        if (attr.dataType.isInstanceOf[NumericType] || attr.dataType.isInstanceOf[StringType]) {
+          val name = attr.name
+          val casted: Expression = attr.dataType match {
+            case StringType => Cast(attr, DoubleType, evalMode = EvalMode.TRY)
+            case _ => attr
+          }
+
+          val approxPercentile = if (percentiles.nonEmpty) {
+            Alias(
+              new ApproximatePercentile(
+                casted,
+                Literal(percentiles.toArray),
+                Literal(ApproximatePercentile.DEFAULT_PERCENTILE_ACCURACY)
+              ).toAggregateExpression(),
+              s"__${name}_approx_percentile__")()
+          } else null

Review Comment:
   I am see a potential issue of NPE. Is there a way that we get rid of `null` here?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -2101,3 +2101,53 @@ object AsOfJoin {
     }
   }
 }
+
+
+/**
+ * A logical plan for summary.
+ */
+case class UnresolvedSummary(
+    child: LogicalPlan,
+    statistics: Seq[String]) extends UnaryNode {
+
+  private lazy val supported =
+    Set("count", "count_distinct", "approx_count_distinct", "mean", "stddev", "min", "max")
+
+  {
+    // TODO: throw AnalysisException instead
+    require(statistics.nonEmpty)
+    val percentiles = statistics.filter(p => p.endsWith("%")).map { p =>
+      try {
+        p.stripSuffix("%").toDouble / 100.0
+      } catch {
+        case e: NumberFormatException =>
+          throw QueryExecutionErrors.cannotParseStatisticAsPercentileError(p, e)
+      }
+    }
+    require(percentiles.forall(p => p >= 0 && p <= 1), "Percentiles must be in the range [0, 1]")
+
+    statistics.foreach {
+      case s if supported.contains(s) =>
+      case p if p.endsWith("%") =>
+      case s => throw QueryExecutionErrors.statisticNotRecognizedError(s)
+    }
+  }
+
+  override protected def stringArgs: Iterator[Any] = super.stringArgs.take(5)
+
+  override lazy val resolved = false // Summary will be replaced after being resolved.
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(SUMMARY)
+
+  override def output: Seq[Attribute] = {
+    AttributeReference("summary", StringType)() +:
+      child.output.flatMap { attr =>
+        if (attr.dataType.isInstanceOf[NumericType] || attr.dataType.isInstanceOf[StringType]) {
+          Some(AttributeReference(attr.name, StringType)())
+        } else None

Review Comment:
   Why we need `None` to  be `placeholder` than just skipping the attribute in the `Summary` outputs?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org