Github user ron8hu commented on a diff in the pull request:

    https://github.com/apache/spark/pull/16395#discussion_r95720653
  
    --- Diff: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala
 ---
    @@ -0,0 +1,555 @@
    +/*
    + * 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.immutable.{HashSet, Map}
    +import scala.collection.mutable
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.plans.logical._
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.types._
    +import org.apache.spark.unsafe.types.UTF8String
    +
    +
    +class FilterEstimation extends Logging {
    +
    +  /**
    +   * We use a mutable colStats because we need to update the corresponding 
ColumnStat
    +   * for a column after we apply a predicate condition.  For example, A 
column c has
    +   * [min, max] value as [0, 100].  In a range condition such as (c > 40 
AND c <= 50),
    +   * we need to set the column's [min, max] value to [40, 100] after we 
evaluate the
    +   * first condition c > 40.  We need to set the column's [min, max] value 
to [40, 50]
    +   * after we evaluate the second condition c <= 50.
    +   */
    +  private var mutableColStats: mutable.Map[ExprId, ColumnStat] = 
mutable.Map.empty
    +
    +  /**
    +   * Returns an option of Statistics for a Filter logical plan node.
    +   * For a given compound expression condition, this method computes 
filter selectivity
    +   * (or the percentage of rows meeting the filter condition), which
    +   * is used to compute row count, size in bytes, and the updated 
statistics after a given
    +   * predicated is applied.
    +   *
    +   * @param plan a LogicalPlan node that must be an instance of Filter.
    +   * @return Option[Statistics] When there is no statistics collected, it 
returns None.
    +   */
    +  def estimate(plan: Filter): Option[Statistics] = {
    +    val stats: Statistics = plan.child.statistics
    +    if (stats.rowCount.isEmpty) return None
    +
    +    // save a mutable copy of colStats so that we can later change it 
recursively
    +    val statsExprIdMap: Map[ExprId, ColumnStat] =
    +      stats.attributeStats.map(kv => (kv._1.exprId, kv._2))
    +    mutableColStats = mutable.Map.empty ++= statsExprIdMap
    +
    +    // estimate selectivity of this filter predicate
    +    val percent: Double = calculateConditions(plan, plan.condition)
    +
    +    // attributeStats has mapping Attribute-to-ColumnStat.
    +    // mutableColStats has mapping ExprId-to-ColumnStat.
    +    // We use an ExprId-to-Attribute map to facilitate the mapping 
Attribute-to-ColumnStat
    +    val expridToAttrMap: Map[ExprId, Attribute] =
    +      stats.attributeStats.map(kv => (kv._1.exprId, kv._1))
    +    // copy mutableColStats contents to an immutable AttributeMap.
    +    val mutableAttributeStats: mutable.Map[Attribute, ColumnStat] =
    +      mutableColStats.map(kv => expridToAttrMap(kv._1) -> kv._2)
    +    val newColStats = AttributeMap(mutableAttributeStats.toSeq)
    +
    +    val filteredRowCountValue: BigInt =
    +      EstimationUtils.ceil(BigDecimal(stats.rowCount.get) * percent)
    +    val avgRowSize = BigDecimal(EstimationUtils.getRowSize(plan.output, 
newColStats))
    +    val filteredSizeInBytes: BigInt =
    +      EstimationUtils.ceil(BigDecimal(filteredRowCountValue) * avgRowSize)
    +
    +    Some(stats.copy(sizeInBytes = filteredSizeInBytes, rowCount = 
Some(filteredRowCountValue),
    +      attributeStats = newColStats))
    +  }
    +
    +  /**
    +   * Returns a percentage of rows meeting a compound condition in Filter 
node.
    +   * A compound condition is depomposed into multiple single conditions 
linked with AND, OR, NOT.
    +   * For logical AND conditions, we need to update stats after a condition 
estimation
    +   * so that the stats will be more accurate for subsequent estimation.  
This is needed for
    +   * range condition such as (c > 40 AND c <= 50)
    +   * For logical OR conditions, we do not update stats after a condition 
estimation.
    +   *
    +   * @param plan the Filter LogicalPlan node
    +   * @param condition the compound logical expression
    +   * @param update a boolean flag to specify if we need to update 
ColumnStat of a column
    +   *               for subsequent conditions
    +   * @return a doube value to show the percentage of rows meeting a given 
condition
    +   */
    +  def calculateConditions(
    +      plan: Filter,
    +      condition: Expression,
    +      update: Boolean = true)
    +    : Double = {
    +
    +    condition match {
    +      case And(cond1, cond2) =>
    +        val p1 = calculateConditions(plan, cond1, update)
    +        val p2 = calculateConditions(plan, cond2, update)
    +        p1 * p2
    +
    +      case Or(cond1, cond2) =>
    +        val p1 = calculateConditions(plan, cond1, update = false)
    +        val p2 = calculateConditions(plan, cond2, update = false)
    +        math.min(1.0, p1 + p2 - (p1 * p2))
    +
    +      case Not(cond) => calculateSingleCondition(plan, cond, isNot = true, 
update = false)
    +      case _ => calculateSingleCondition(plan, condition, isNot = false, 
update)
    +    }
    +  }
    +
    +  /**
    +   * Returns a percentage of rows meeting a single condition in Filter 
node.
    +   * Currently we only support binary predicates where one side is a 
column,
    +   * and the other is a literal.
    +   *
    +   * @param plan the Filter LogicalPlan node
    +   * @param condition a single logical expression
    +   * @param isNot set to true for "IS NULL" condition.  set to false for 
"IS NOT NULL" condition
    +   * @param update a boolean flag to specify if we need to update 
ColumnStat of a column
    +   *               for subsequent conditions
    +   * @return a doube value to show the percentage of rows meeting a given 
condition
    +   */
    +  def calculateSingleCondition(
    +      plan: Filter,
    +      condition: Expression,
    +      isNot: Boolean,
    --- End diff --
    
    My comments in the code were misleading.  I revised them.  IsNot is set to 
true to handle NOT logical operator.  


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

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

Reply via email to