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 2020/11/15 12:00:28 UTC

[GitHub] [spark] maropu commented on a change in pull request #30334: [SPARK-33411][SQL] Cardinality estimation of union, sort and range operator

maropu commented on a change in pull request #30334:
URL: https://github.com/apache/spark/pull/30334#discussion_r523745990



##########
File path: sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala
##########
@@ -531,7 +531,7 @@ class StatisticsCollectionSuite extends StatisticsCollectionTestBase with Shared
 
       // Cache the view then analyze it
       sql("CACHE TABLE tempView")
-      assert(getStatAttrNames("tempView") !== Set("id"))
+      assert(getStatAttrNames("tempView") === Set("id"))

Review comment:
       hm, could you update the query above `sql("CREATE TEMPORARY VIEW tempView AS SELECT * FROM range(1, 30)")` ? The update in this PR seems to make this test meaningless.

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala
##########
@@ -545,7 +545,33 @@ case class Range(
   }
 
   override def computeStats(): Statistics = {
-    Statistics(sizeInBytes = LongType.defaultSize * numElements)
+    val minVal = if (step > 0) {
+      start
+    } else {
+      start + (numElements - 1) * step
+    }
+
+    val maxVal = if (step > 0) {
+      start + (numElements - 1) * step
+    } else {
+      start
+    }
+
+    Statistics(
+      sizeInBytes = LongType.defaultSize * numElements,
+      rowCount = Some(numElements),
+      attributeStats = AttributeMap(
+        output.map(
+          a =>
+            (
+              a,
+              ColumnStat(
+                distinctCount = Some(numElements),
+                max = Some(maxVal),
+                min = Some(minVal),
+                nullCount = Some(0),
+                avgLen = Some(LongType.defaultSize),
+                maxLen = Some(LongType.defaultSize))))))

Review comment:
       nit format: How about this?
   ```
       if (numElements == 0) {
         Statistics(sizeInBytes = 0L)
       } else {
         val (minVal, maxVal) = if (step > 0) {
           (start, start + (numElements - 1) * step)
         } else {
           (start + (numElements - 1) * step, start)
         }
         val colStat = ColumnStat(
           distinctCount = Some(numElements),
           max = Some(maxVal),
           min = Some(minVal),
           nullCount = Some(0),
           avgLen = Some(LongType.defaultSize),
           maxLen = Some(LongType.defaultSize))
   
         Statistics(
           sizeInBytes = LongType.defaultSize * numElements,
           rowCount = Some(numElements),
           attributeStats = AttributeMap(Seq(output.head -> colStat)))
       }
   ```

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/UnionEstimation.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.plans.logical.statsEstimation
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics, Union}
+
+object UnionEstimation {
+  import EstimationUtils._
+
+  def compare(a: Any, b: Any): Boolean = {

Review comment:
       Could you use `AtomicType.ordering.compare` instead?

##########
File path: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/BasicStatsEstimationSuite.scala
##########
@@ -42,13 +42,44 @@ class BasicStatsEstimationSuite extends PlanTest with StatsEstimationTestBase {
     // row count * (overhead + column size)
     size = Some(10 * (8 + 4)))
 
-  test("range") {
+  test("range with positive step") {
     val range = Range(1, 5, 1, None)
-    val rangeStats = Statistics(sizeInBytes = 4 * 8)
-    checkStats(
-      range,
-      expectedStatsCboOn = rangeStats,
-      expectedStatsCboOff = rangeStats)
+    val rangeStats = Statistics(
+      sizeInBytes = 4 * 8,
+      rowCount = Some(4),
+      attributeStats = AttributeMap(
+        range.output.map(
+          attr =>
+            (
+              attr,
+              ColumnStat(
+                distinctCount = Some(4),
+                min = Some(1),
+                max = Some(4),
+                nullCount = Some(0),
+                maxLen = Some(LongType.defaultSize),
+                avgLen = Some(LongType.defaultSize))))))
+    checkStats(range, expectedStatsCboOn = rangeStats, expectedStatsCboOff = rangeStats)
+  }
+
+  test("range with negative step") {
+    val range = Range(-10, -20, -2, None)

Review comment:
       ditto: Could you add tests for the case `(end - start) % step != 0`, too?

##########
File path: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/SortEstimationSuite.scala
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.statsEstimation
+
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.plans.logical
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Sort}
+import org.apache.spark.sql.types.{BooleanType, ByteType}
+
+class SortEstimationSuite extends StatsEstimationTestBase {
+
+  test("test row size and column stats estimation") {

Review comment:
       Could you add this test in `BasicStatsEstimationSuite` instead of making a new file?

##########
File path: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/BasicStatsEstimationSuite.scala
##########
@@ -42,13 +42,44 @@ class BasicStatsEstimationSuite extends PlanTest with StatsEstimationTestBase {
     // row count * (overhead + column size)
     size = Some(10 * (8 + 4)))
 
-  test("range") {
+  test("range with positive step") {
     val range = Range(1, 5, 1, None)

Review comment:
       Could you add tests for the case `(end - start) % step != 0`, too?

##########
File path: sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala
##########
@@ -553,7 +553,7 @@ class StatisticsCollectionSuite extends StatisticsCollectionTestBase with Shared
 
       // Cache the view then analyze it
       sql(s"CACHE TABLE $globalTempDB.gTempView")
-      assert(getStatAttrNames(s"$globalTempDB.gTempView") !== Set("id"))
+      assert(getStatAttrNames(s"$globalTempDB.gTempView") === Set("id"))

Review comment:
       ditto

##########
File path: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/BasicStatsEstimationSuite.scala
##########
@@ -42,13 +42,44 @@ class BasicStatsEstimationSuite extends PlanTest with StatsEstimationTestBase {
     // row count * (overhead + column size)
     size = Some(10 * (8 + 4)))
 
-  test("range") {
+  test("range with positive step") {
     val range = Range(1, 5, 1, None)
-    val rangeStats = Statistics(sizeInBytes = 4 * 8)
-    checkStats(
-      range,
-      expectedStatsCboOn = rangeStats,
-      expectedStatsCboOff = rangeStats)
+    val rangeStats = Statistics(
+      sizeInBytes = 4 * 8,
+      rowCount = Some(4),
+      attributeStats = AttributeMap(
+        range.output.map(
+          attr =>
+            (
+              attr,
+              ColumnStat(
+                distinctCount = Some(4),
+                min = Some(1),
+                max = Some(4),
+                nullCount = Some(0),
+                maxLen = Some(LongType.defaultSize),
+                avgLen = Some(LongType.defaultSize))))))
+    checkStats(range, expectedStatsCboOn = rangeStats, expectedStatsCboOff = rangeStats)
+  }
+
+  test("range with negative step") {

Review comment:
       Could you add tests for an empty case? 
   ```
   scala> sql("select * from range(1, 1, 3)").show()
   +---+
   | id|
   +---+
   +---+
   ```

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/UnionEstimation.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.plans.logical.statsEstimation
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics, Union}
+
+object UnionEstimation {
+  import EstimationUtils._
+
+  def compare(a: Any, b: Any): Boolean = {
+    a match {
+      case _: Int => a.asInstanceOf[Int] < b.asInstanceOf[Int]
+      case _: Long => a.asInstanceOf[Long] < b.asInstanceOf[Long]
+      case _: Float => a.asInstanceOf[Float] < b.asInstanceOf[Float]
+      case _: Double => a.asInstanceOf[Double] < b.asInstanceOf[Double]
+      case _: Short => a.asInstanceOf[Short] < b.asInstanceOf[Short]
+      case _: Byte => a.asInstanceOf[Byte] < b.asInstanceOf[Byte]

Review comment:
       How about `decimal`, `date` and `timestamp`?

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/UnionEstimation.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.plans.logical.statsEstimation
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics, Union}
+
+object UnionEstimation {

Review comment:
       Could you leave some comments about how to estimate `Union` stats here?

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/UnionEstimation.scala
##########
@@ -0,0 +1,87 @@
+/*
+ * 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.plans.logical.statsEstimation
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics, Union}
+
+object UnionEstimation {
+  import EstimationUtils._
+
+  def compare(a: Any, b: Any): Boolean = {
+    a match {
+      case _: Int => a.asInstanceOf[Int] < b.asInstanceOf[Int]
+      case _: Long => a.asInstanceOf[Long] < b.asInstanceOf[Long]
+      case _: Float => a.asInstanceOf[Float] < b.asInstanceOf[Float]
+      case _: Double => a.asInstanceOf[Double] < b.asInstanceOf[Double]
+      case _: Short => a.asInstanceOf[Short] < b.asInstanceOf[Short]
+      case _: Byte => a.asInstanceOf[Byte] < b.asInstanceOf[Byte]
+      case _ => false
+    }
+  }
+
+  def estimate(union: Union): Option[Statistics] = {
+    val sizeInBytes = union.children.map(_.stats.sizeInBytes).sum
+    val outputRows: Option[BigInt] = if (rowCountsExist(union.children: _*)) {
+      Some(union.children.map(_.stats.rowCount.get).sum)
+    } else {
+      None
+    }
+
+    val output = union.output
+    val outputAttrStats = new ArrayBuffer[(Attribute, ColumnStat)]()
+
+    union.children.map(_.output).transpose.zipWithIndex.foreach {
+      case (attrs, outputIndex) =>
+        val validStat = attrs.zipWithIndex.forall {
+          case (attr, childIndex) =>
+            val attrStats = union.children(childIndex).stats.attributeStats
+            attrStats.get(attr).isDefined && attrStats(attr).hasMinMaxStats
+        }
+        if (validStat) {
+          var min: Option[Any] = None
+          var max: Option[Any] = None
+          attrs.zipWithIndex.foreach {

Review comment:
       To avoid `var`, could you use `foldLeft` here?

##########
File path: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/UnionEstimationSuite.scala
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.statsEstimation
+
+import org.apache.spark.sql.catalyst.expressions.{AttributeMap, AttributeReference}
+import org.apache.spark.sql.catalyst.plans.logical
+import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Union}
+import org.apache.spark.sql.types.{DoubleType, IntegerType}
+
+class UnionEstimationSuite extends StatsEstimationTestBase {
+
+  test("test row size estimation") {
+    val attrInt = AttributeReference("cint", IntegerType)()
+
+    val sz: Option[BigInt] = Some(1024)
+    val child1 = StatsTestPlan(
+      outputList = Seq(attrInt),
+      rowCount = 2,
+      attributeStats = AttributeMap(Nil),
+      size = sz)
+
+    val child2 = StatsTestPlan(
+      outputList = Seq(attrInt),
+      rowCount = 2,
+      attributeStats = AttributeMap(Nil),
+      size = sz)
+
+    val union = Union(Seq(child1, child2))
+    val expectedStats = logical.Statistics(sizeInBytes = 2 * 1024, rowCount = Some(4))
+    assert(union.stats === expectedStats)
+  }
+
+  test("col stats estimation") {
+    val sz: Option[BigInt] = Some(1024)
+
+    val attrInt = AttributeReference("cint", IntegerType)()
+    val attrDouble = AttributeReference("cdouble", DoubleType)()

Review comment:
       Could you add tests for all the supported types?




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

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