spark-reviews mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From HyukjinKwon <...@git.apache.org>
Subject [GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...
Date Fri, 16 Sep 2016 06:32:33 GMT
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79112828
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala
---
    @@ -0,0 +1,209 @@
    +/*
    + * 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.command
    +
    +import scala.collection.mutable
    +
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.plans.logical.{BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.functions._
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table in the current database to generate
statistics,
    + * which will be used in query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableName: String,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val tableIdent = sessionState.sqlParser.parseTableIdentifier(tableName)
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness for column names
    +    val attributeNames = relation.output.map(_.name.toLowerCase)
    +    val invalidColumns = columnNames.filterNot { col => attributeNames.contains(col.toLowerCase)}
    +    if (invalidColumns.nonEmpty) {
    +      throw new AnalysisException(s"Invalid columns for table $tableName: $invalidColumns.")
    +    }
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sparkSession, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException(s"ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val lowerCaseNames = columnNames.map(_.toLowerCase)
    +      val attributes =
    +        relation.output.filter(attr => lowerCaseNames.contains(attr.name.toLowerCase))
    +
    +      // collect column statistics
    +      val aggColumns = mutable.ArrayBuffer[Column](count(Column("*")))
    +      attributes.foreach(entry => aggColumns ++= statsAgg(entry.name, entry.dataType))
    +      val statsRow: InternalRow = Dataset.ofRows(sparkSession, relation).select(aggColumns:
_*)
    +        .queryExecution.toRdd.collect().head
    +
    +      // We also update table-level stats to prevent inconsistency in case of table modification
    +      // between the two ANALYZE commands for collecting table-level stats and column-level
stats.
    +      val rowCount = statsRow.getLong(0)
    +      var newStats: Statistics = if (catalogTable.stats.isDefined) {
    +        catalogTable.stats.get.copy(sizeInBytes = newTotalSize, rowCount = Some(rowCount))
    +      } else {
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount))
    +      }
    +
    +      var pos = 1
    +      val colStats = mutable.HashMap[String, BasicColStats]()
    +      attributes.foreach { attr =>
    +        attr.dataType match {
    +          case n: NumericType =>
    +            colStats += attr.name -> BasicColStats(
    +              dataType = attr.dataType,
    +              numNulls = rowCount - statsRow.getLong(pos + NumericStatsAgg.numNotNullsIndex),
    +              max = Option(statsRow.get(pos + NumericStatsAgg.maxIndex, attr.dataType)),
    +              min = Option(statsRow.get(pos + NumericStatsAgg.minIndex, attr.dataType)),
    +              ndv = Some(statsRow.getLong(pos + NumericStatsAgg.ndvIndex)))
    +            pos += NumericStatsAgg.statsSeq.length
    +          case TimestampType | DateType =>
    +            colStats += attr.name -> BasicColStats(
    +              dataType = attr.dataType,
    +              numNulls = rowCount - statsRow.getLong(pos + NumericStatsAgg.numNotNullsIndex),
    +              max = Option(statsRow.get(pos + NumericStatsAgg.maxIndex, attr.dataType)),
    +              min = Option(statsRow.get(pos + NumericStatsAgg.minIndex, attr.dataType)),
    +              ndv = Some(statsRow.getLong(pos + NumericStatsAgg.ndvIndex)))
    +            pos += NumericStatsAgg.statsSeq.length
    +          case StringType =>
    +            colStats += attr.name -> BasicColStats(
    +              dataType = attr.dataType,
    +              numNulls = rowCount - statsRow.getLong(pos + StringStatsAgg.numNotNullsIndex),
    +              maxColLen = Some(statsRow.getLong(pos + StringStatsAgg.maxLenIndex)),
    +              avgColLen =
    +                Some(statsRow.getLong(pos + StringStatsAgg.sumLenIndex) / (1.0 * rowCount)),
    +              ndv = Some(statsRow.getLong(pos + StringStatsAgg.ndvIndex)))
    +            pos += StringStatsAgg.statsSeq.length
    +          case BinaryType =>
    +            colStats += attr.name -> BasicColStats(
    +              dataType = attr.dataType,
    +              numNulls = rowCount - statsRow.getLong(pos + BinaryStatsAgg.numNotNullsIndex),
    +              maxColLen = Some(statsRow.getLong(pos + BinaryStatsAgg.maxLenIndex)),
    +              avgColLen =
    +                Some(statsRow.getLong(pos + BinaryStatsAgg.sumLenIndex) / (1.0 * rowCount)))
    +            pos += BinaryStatsAgg.statsSeq.length
    +          case BooleanType =>
    +            val numOfNotNulls = statsRow.getLong(pos + BooleanStatsAgg.numNotNullsIndex)
    +            val numOfTrues = Some(statsRow.getLong(pos + BooleanStatsAgg.numTruesIndex))
    +            colStats += attr.name -> BasicColStats(
    +              dataType = attr.dataType,
    +              numNulls = rowCount - numOfNotNulls,
    +              numTrues = numOfTrues,
    +              numFalses = numOfTrues.map(i => numOfNotNulls - i),
    +              ndv = Some(2))
    +            pos += BooleanStatsAgg.statsSeq.length
    +        }
    +      }
    +      newStats = newStats.copy(basicColStats = colStats.toMap)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(newStats)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  private def statsAgg(name: String, dataType: DataType): Seq[Column] = dataType match
{
    +    // Currently we only support stats generation for atomic types
    +    case n: NumericType => NumericStatsAgg(name)
    +    case TimestampType | DateType => NumericStatsAgg(name)
    +    case StringType => StringStatsAgg(name)
    +    case BinaryType => BinaryStatsAgg(name)
    +    case BooleanType => BooleanStatsAgg(name)
    +    case otherType =>
    +      throw new AnalysisException(s"Analyzing column $name of $otherType is not supported.")
    +  }
    +}
    +
    +object ColumnStats extends Enumeration {
    --- End diff --
    
    I guess it is not encouraged to add `private[sql]` in this case. Please see https://github.com/apache/spark/commit/511f52f8423e151b0d0133baf040d34a0af3d422#diff-04b333ef6416de455e072b2bbbeff9efL37


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


Mime
View raw message