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 2021/12/13 07:31:33 UTC

[GitHub] [spark] zhengruifeng commented on a change in pull request #34367: [SPARK-37099][SQL] Impl a rank-based filter to optimize top-k computation

zhengruifeng commented on a change in pull request #34367:
URL: https://github.com/apache/spark/pull/34367#discussion_r767467761



##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/window/RankLimitExec.scala
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.execution.window
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.codegen._
+import org.apache.spark.sql.catalyst.plans.physical._
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.metric.SQLMetrics
+import org.apache.spark.util.collection.Utils
+
+
+sealed trait RankLimitMode
+
+case object Partial extends RankLimitMode
+
+case object Final extends RankLimitMode
+
+
+
+/**
+ * This operator is designed to filter out unnecessary rows before WindowExec,
+ * for top-k computation.
+ * @param partitionSpec Should be the same as [[WindowExec#partitionSpec]]
+ * @param orderSpec Should be the same as [[WindowExec#orderSpec]]
+ * @param rankFunction The function to compute row rank, should be RowNumber/Rank/DenseRank.
+ */
+case class RankLimitExec(
+    partitionSpec: Seq[Expression],
+    orderSpec: Seq[SortOrder],
+    rankFunction: Expression,
+    limit: Int,
+    mode: RankLimitMode,
+    child: SparkPlan) extends UnaryExecNode {
+  assert(orderSpec.nonEmpty && limit > 0)
+
+  private val shouldPass = child match {
+    case r: RankLimitExec =>
+      partitionSpec.size == r.partitionSpec.size &&
+        partitionSpec.zip(r.partitionSpec).forall(p => p._1.semanticEquals(p._2)) &&
+        orderSpec.size == r.orderSpec.size &&
+        orderSpec.zip(r.orderSpec).forall(o => o._1.semanticEquals(o._2)) &&
+        rankFunction.semanticEquals(r.rankFunction) &&
+        mode == Final && r.mode == Partial && limit == r.limit
+    case _ => false
+  }
+
+  private val shouldApplyTakeOrdered: Boolean = {
+    rankFunction match {
+      case _: RowNumber => limit < conf.topKSortFallbackThreshold
+      case _: Rank => false
+      case _: DenseRank => false
+      case f => throw new IllegalArgumentException(s"Unsupported rank function: $f")
+    }
+  }
+
+  override def output: Seq[Attribute] = child.output
+
+  override def requiredChildOrdering: Seq[Seq[SortOrder]] = {
+    if (shouldApplyTakeOrdered) {
+      Seq(partitionSpec.map(SortOrder(_, Ascending)))
+    } else {
+      // Should be the same as [[WindowExec#requiredChildOrdering]]
+      Seq(partitionSpec.map(SortOrder(_, Ascending)) ++ orderSpec)
+    }
+  }
+
+  override def outputOrdering: Seq[SortOrder] = {
+    partitionSpec.map(SortOrder(_, Ascending)) ++ orderSpec
+  }
+
+  override def requiredChildDistribution: Seq[Distribution] = mode match {
+    case Partial => super.requiredChildDistribution
+    case Final =>
+      // Should be the same as [[WindowExec#requiredChildDistribution]]
+      if (partitionSpec.isEmpty) {
+        AllTuples :: Nil
+      } else ClusteredDistribution(partitionSpec) :: Nil
+  }
+
+  override def outputPartitioning: Partitioning = child.outputPartitioning
+
+  override lazy val metrics = Map(
+    "numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows"))
+
+  private lazy val ordering = GenerateOrdering.generate(orderSpec, output)
+
+  private lazy val limitFunction = rankFunction match {
+    case _: RowNumber if shouldApplyTakeOrdered =>
+      (stream: Iterator[InternalRow]) =>
+        Utils.takeOrdered(stream.map(_.copy()), limit)(ordering)

Review comment:
         ```
   val TOP_K_SORT_FALLBACK_THRESHOLD =
       buildConf("spark.sql.execution.topKSortFallbackThreshold")
         .doc("In SQL queries with a SORT followed by a LIMIT like " +
             "'SELECT x FROM t ORDER BY y LIMIT m', if m is under this threshold, do a top-K sort" +
             " in memory, otherwise do a global sort which spills to disk if necessary.")
         .version("2.4.0")
         .intConf
         .createWithDefault(ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH)
   ```
   
   I think we can still share the same threshold. The problem is that its default value is too high, which should be set to a relative smaller number in practice, such as 10000.




-- 
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