You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by wzhfy <gi...@git.apache.org> on 2016/09/14 03:56:16 UTC

[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

GitHub user wzhfy opened a pull request:

    https://github.com/apache/spark/pull/15090

    [SPARK-17073] [SQL] generate column-level statistics

    ## What changes were proposed in this pull request?
    
    Generate basic column statistics for all the atomic types:
    - numeric types: max, min, num of nulls, ndv (number of distinct values)
    - date/timestamp types: they are also represented as numbers internally, so they have the same stats as above.
    - string: avg length, max length, num of nulls, ndv
    - binary: avg length, max length, num of nulls
    - boolean: num of nulls, num of trues, num of falsies, ndv (must be 2)
    
    Also support storing and loading these statistics.
    
    ## How was this patch tested?
    
    add unit tests

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/wzhfy/spark colStats

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/15090.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #15090
    
----
commit 59ae3dfc45751705962a1370c195c67c6302c376
Author: Zhenhua Wang <wz...@163.com>
Date:   2016-09-14T03:03:05Z

    support column-level stats

----


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65746/
    Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Actually, I didn't mean to approve immediately, sorry.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81275778
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    --- End diff --
    
    How about issuing `logWarning`? I still think a silent drop is a concern


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79766674
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,28 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    +   * Create an [[AnalyzeTableCommand]] command or an [[AnalyzeColumnCommand]] command.
    +   * Example SQL for analyzing table :
        * {{{
        *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    +   *   ANALYZE TABLE table COMPUTE STATISTICS;
    --- End diff --
    
    You can combine them by `ANALYZE TABLE table COMPUTE STATISTICS [NOSCAN];`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79331169
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    `assert(colStats.ndv.get >= 0)` might be too loose. Can we check if it is more than 0 and less than the number of values in the column?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79707997
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,19 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    -   * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    -   * }}}
    --- End diff --
    
    This is to show the syntax we support. You can check almost all the DDL, we put the syntax before the function. It can help others understand your implementation.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79925435
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    +    min: Option[Any] = None,
    +    ndv: Option[Long] = None,
    +    avgColLen: Option[Double] = None,
    +    maxColLen: Option[Long] = None,
    +    numTrues: Option[Long] = None,
    --- End diff --
    
    For boolean type, we don't need histograms, we can just use these two values.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81100678
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    --- End diff --
    
    is it a common behaviour? i.e. if users specify duplicated columns, we just deduplicate silently instead of reporting error.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78708563
  
    --- 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 {
    +  val MAX, MIN, NDV, NUM_NOT_NULLS, MAX_LENGTH, SUM_LENGTH, NUM_TRUES = Value
    +}
    +
    +trait StatsAggFunc {
    +  // This sequence is used to track the order of stats results when collecting.
    +  val statsSeq: Seq[ColumnStats.Value]
    +
    +  def apply(name: String): Seq[Column] = {
    +    val col = Column(name)
    +    statsSeq.map {
    +      case ColumnStats.MAX => max(col)
    +      case ColumnStats.MIN => min(col)
    +      // count(distinct col) will have a shuffle, so we use an approximate ndv for efficiency
    +      case ColumnStats.NDV => approxCountDistinct(col)
    --- End diff --
    
    HyperLogLogPlusPlus supports an error parameter and we also exposed this to the end user.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78686462
  
    --- 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 {
    +  val MAX, MIN, NDV, NUM_NOT_NULLS, MAX_LENGTH, SUM_LENGTH, NUM_TRUES = Value
    +}
    +
    +trait StatsAggFunc {
    +  // This sequence is used to track the order of stats results when collecting.
    +  val statsSeq: Seq[ColumnStats.Value]
    +
    +  def apply(name: String): Seq[Column] = {
    +    val col = Column(name)
    +    statsSeq.map {
    +      case ColumnStats.MAX => max(col)
    +      case ColumnStats.MIN => min(col)
    +      // count(distinct col) will have a shuffle, so we use an approximate ndv for efficiency
    +      case ColumnStats.NDV => approxCountDistinct(col)
    --- End diff --
    
    The error rate of the estimation should be tunable, right? See Hive has such a configuration: `hive.stats.ndv.error�`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79329866
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val two = Literal(2, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: Expression, relativeSD: Double): CreateStruct = {
    +    var statistics = e.dataType match {
    +      case n: NumericType =>
    --- End diff --
    
    @wzhfy Hm. Are you doubly sure that causes compilation error? I just checked out your PR and it seems compiling fine.
    
    ```
          case _: NumericType | TimestampType | DateType =>
            Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
              nullLong)
    ```
    
    If you keep `n` variable then it will cause a compilation error but if we don't use this, it'd be fine.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65746 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65746/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79921689
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: NamedExpression, relativeSD: Double): CreateStruct = {
    +    // Use aggregate functions to compute statistics we need:
    +    // - number of nulls: Sum(If(IsNull(e), one, zero));
    +    // - maximum value: Max(e);
    +    // - minimum value: Min(e);
    +    // - ndv (number of distinct values): HyperLogLogPlusPlus(e, relativeSD);
    +    // - average length of values: Average(Length(e));
    +    // - maximum length of values: Max(Length(e));
    +    // - number of true values: Sum(If(e, one, zero));
    +    // - number of false values: Sum(If(Not(e), one, zero));
    +    // - If we don't need some statistic for the data type, use null literal.
    +    // Note that: the order of each sequence must be as follows:
    +    // numNulls, max, min, ndv, avgColLen, maxColLen, numTrues, numFalses
    +    var statistics = e.dataType match {
    +      case _: NumericType | TimestampType | DateType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    --- End diff --
    
    Should we tamp the NDV estimate by the number of rows in the dataset ?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79893014
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    +    min: Option[Any] = None,
    +    ndv: Option[Long] = None,
    +    avgColLen: Option[Double] = None,
    +    maxColLen: Option[Long] = None,
    +    numTrues: Option[Long] = None,
    +    numFalses: Option[Long] = None) {
    +
    +  override def toString: String = "ColumnStats(" + simpleString + ")"
    +
    +  def simpleString: String = {
    +    Seq(s"numNulls=$numNulls",
    +      if (max.isDefined) s"max=${max.get}" else "",
    +      if (min.isDefined) s"min=${min.get}" else "",
    +      if (ndv.isDefined) s"ndv=${ndv.get}" else "",
    +      if (avgColLen.isDefined) s"avgColLen=${avgColLen.get}" else "",
    +      if (maxColLen.isDefined) s"maxColLen=${maxColLen.get}" else "",
    +      if (numTrues.isDefined) s"numTrues=${numTrues.get}" else "",
    +      if (numFalses.isDefined) s"numFalses=${numFalses.get}" else ""
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +object ColumnStats {
    +  def fromString(str: String, dataType: DataType): ColumnStats = {
    --- End diff --
    
    Suggestion: Based on fromString, It looks like simpleString above is practically used as a serializer to stuff stats in the catalog ? If so, could you change the name to catalogRepresentation or something like that so it's clear.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    @rxin Because we want to test storing/loading these stats from metastore, and make sure they are right after we load them into our catalogTable.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66131/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78731826
  
    --- 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
    --- End diff --
    
    If you want the internal types call `executeCollect`. That leads to the following question, do we want to store internal representations in the metastore?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78688956
  
    --- 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 {
    +  val MAX, MIN, NDV, NUM_NOT_NULLS, MAX_LENGTH, SUM_LENGTH, NUM_TRUES = Value
    +}
    +
    +trait StatsAggFunc {
    +  // This sequence is used to track the order of stats results when collecting.
    +  val statsSeq: Seq[ColumnStats.Value]
    +
    +  def apply(name: String): Seq[Column] = {
    +    val col = Column(name)
    +    statsSeq.map {
    +      case ColumnStats.MAX => max(col)
    +      case ColumnStats.MIN => min(col)
    +      // count(distinct col) will have a shuffle, so we use an approximate ndv for efficiency
    +      case ColumnStats.NDV => approxCountDistinct(col)
    --- End diff --
    
    This needs an external API interface change. Let us let the Committers make the decision. cc @rxin @hvanhovell @cloud-fan 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81102672
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala ---
    @@ -581,6 +581,13 @@ object SQLConf {
           .timeConf(TimeUnit.MILLISECONDS)
           .createWithDefault(10L)
     
    +  val NDV_MAX_ERROR =
    +    SQLConfigBuilder("spark.sql.statistics.ndv.maxError")
    +      .internal()
    +      .doc("The maximum estimation error allowed in HyperLogLog++ algorithm.")
    --- End diff --
    
    should we mention that this conf is only used to generate column level statistics?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65941/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79296707
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val two = Literal(2, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: Expression, relativeSD: Double): CreateStruct = {
    +    var statistics = e.dataType match {
    +      case n: NumericType =>
    --- End diff --
    
    This will cause compilation error: illegal variable in pattern alternative



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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81259329
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,354 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    def assertAnalyzeColumnCommand(analyzeCommand: String, c: Class[_]) {
    +      val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +      val operators = parsed.collect {
    +        case a: AnalyzeColumnCommand => a
    +        case o => o
    +      }
    +      assert(operators.size == 1)
    +      if (operators.head.getClass != c) {
    --- End diff --
    
    I don't think it's a good style, parsing a SQL string and constructing an expected logical plan and then compare them looks much clearer.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    has an offline discussion with @wzhfy , here is the result:
    
    1. The current `ColumnStats` is hard to use because most of its fields are `Option`, some are `Option[Any]`, and we may need a lot of pattern match to use them.
    2. If we use `InternalRow` directly, we may need to write a lot of comments at caller side, e.g. we need to explain `columnStats.getInt(0)` is to get the max value.
    
    a new proposal:
    We can still use `InternalRow` to represent column statistics, and provide some util functions to construct a "getter" for it. e.g.
    ```
    object ColumnStats {
      def forBooleanColumn(statsRow: InternalRow): BooleanColumnStatus = ...
      def forStringColumn(statsRow: InternalRow): StringColumnStatus = ...
      def forNumericColumn[T <: Number] ...
      ......
    }
    
    class BooleanColumnStats(statsRow) {
      def numTrues = statsRow.getLong(0)
      ......
    }
    
    ```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79166502
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    you can also check if the value is within 3 standard deviations.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80639243
  
    --- Diff: sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveExternalCatalog.scala ---
    @@ -473,15 +476,20 @@ private[spark] class HiveExternalCatalog(conf: SparkConf, hadoopConf: Configurat
           }
         }
         // construct Spark's statistics from information in Hive metastore
    -    if (catalogTable.properties.contains(STATISTICS_TOTAL_SIZE)) {
    -      val totalSize = BigInt(catalogTable.properties.get(STATISTICS_TOTAL_SIZE).get)
    -      // TODO: we will compute "estimatedSize" when we have column stats:
    -      // average size of row * number of rows
    +    if (catalogTable.properties.filterKeys(_.startsWith(STATISTICS_PREFIX)).nonEmpty) {
    +      val colStatsProps = catalogTable.properties
    +        .filterKeys(_.startsWith(STATISTICS_BASIC_COL_STATS_PREFIX))
    +        .map { case (k, v) => (k.replace(STATISTICS_BASIC_COL_STATS_PREFIX, ""), v) }
    --- End diff --
    
    I think it's safer to do `k.drop(STATISTICS_BASIC_COL_STATS_PREFIX.length)`


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65347/
    Test FAILed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Although no conflict is detected, we should still fetch and merge the latest master. Then, the changes made in `DataSourceStrategy.scala` will disappaer.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80639732
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    --- End diff --
    
    ah i see


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79330219
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val two = Literal(2, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: Expression, relativeSD: Double): CreateStruct = {
    +    var statistics = e.dataType match {
    +      case n: NumericType =>
    --- End diff --
    
    Oh, I made a mistake, thanks! @HyukjinKwon 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66188 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66188/consoleFull)** for PR 15090 at commit [`95c2d2f`](https://github.com/apache/spark/commit/95c2d2fab6f24d433aedf6d4a3d28de69d6c2889).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78685367
  
    --- 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 " +
    --- End diff --
    
    This `s` is useless. Right?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78730873
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeTableCommand.scala ---
    @@ -129,3 +87,51 @@ case class AnalyzeTableCommand(tableName: String, noscan: Boolean = true) extend
         Seq.empty[Row]
       }
     }
    +
    +object AnalyzeTableCommand extends Logging {
    --- End diff --
    
    Why move this?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78717889
  
    --- 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)
    --- End diff --
    
    They can be different. Although `case sensitive` is not very well supported. 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65994 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65994/consoleFull)** for PR 15090 at commit [`377a491`](https://github.com/apache/spark/commit/377a4919f43f6da86f1dd7c0d121d0436d377431).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `case class ColumnStat(statRow: InternalRow) `


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65633 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65633/consoleFull)** for PR 15090 at commit [`0f974c0`](https://github.com/apache/spark/commit/0f974c019401ac5cef1be1b1e69a523ee2287101).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78731424
  
    --- 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))
    --- End diff --
    
    What alias are you removing here? 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65690 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65690/consoleFull)** for PR 15090 at commit [`392a312`](https://github.com/apache/spark/commit/392a312dd3dd606d6cfa9f96af246d718fc0fb42).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65745 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65745/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    LGTM except for one minor comment regarding ndv config document.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81183331
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    --- End diff --
    
    Yes, hive does so. @hvanhovell and @gatorsmile also agreed on this.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80165466
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
    --- End diff --
    
    BTW, I've created a jira for this. We can fix it when column-level statistics including histograms are supported.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    @rxin Thanks, I'll fix them in the followup pr.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78688327
  
    --- 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 {
    +  val MAX, MIN, NDV, NUM_NOT_NULLS, MAX_LENGTH, SUM_LENGTH, NUM_TRUES = Value
    +}
    +
    +trait StatsAggFunc {
    +  // This sequence is used to track the order of stats results when collecting.
    +  val statsSeq: Seq[ColumnStats.Value]
    +
    +  def apply(name: String): Seq[Column] = {
    +    val col = Column(name)
    +    statsSeq.map {
    +      case ColumnStats.MAX => max(col)
    +      case ColumnStats.MIN => min(col)
    +      // count(distinct col) will have a shuffle, so we use an approximate ndv for efficiency
    +      case ColumnStats.NDV => approxCountDistinct(col)
    --- End diff --
    
    HyperLogLogPlusPlus has a param to control the error, but it's not configurable currently in spark sql, shall we add this conf?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79550951
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsTest.scala ---
    @@ -0,0 +1,139 @@
    +/*
    + * 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.hive
    +
    +import org.apache.spark.sql.{DataFrame, QueryTest}
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.command.{AnalyzeColumnCommand, AnalyzeTableCommand}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.hive.test.TestHiveSingleton
    +import org.apache.spark.sql.test.SQLTestUtils
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with TestHiveSingleton with SQLTestUtils {
    +
    +  def assertAnalyzeCommand(analyzeCommand: String, c: Class[_]) {
    +    val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +    val operators = parsed.collect {
    +      case a: AnalyzeTableCommand => a
    +      case b: AnalyzeColumnCommand => b
    +      case o => o
    --- End diff --
    
    ? 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81454078
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsTest.scala ---
    @@ -0,0 +1,129 @@
    +/*
    + * 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
    +
    +import org.apache.spark.sql.catalyst.TableIdentifier
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics}
    +import org.apache.spark.sql.execution.command.{AnalyzeColumnCommand, ColumnStatStruct}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with SharedSQLContext {
    +
    +  def checkColStats(
    +      df: DataFrame,
    +      expectedColStatsSeq: Seq[(StructField, ColumnStat)]): Unit = {
    +    val table = "tbl"
    +    withTable(table) {
    +      df.write.format("json").saveAsTable(table)
    +      val columns = expectedColStatsSeq.map(_._1)
    +      val tableIdent = TableIdentifier(table, Some("default"))
    +      val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +      val columnStats =
    +        AnalyzeColumnCommand(tableIdent, columns.map(_.name)).computeColStats(spark, relation)._2
    --- End diff --
    
    Nit:
    ```Scala
            val (_, columnStats) =
              AnalyzeColumnCommand(tableIdent, columnsToAnalyze).computeColStats(spark, relation)
    ```


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65746 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65746/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79965497
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsTest.scala ---
    @@ -0,0 +1,88 @@
    +/*
    + * 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
    +
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with SharedSQLContext {
    +
    +  def checkColStats(
    +      df: DataFrame,
    +      expectedColStatsSeq: Seq[(String, ColumnStats)]): Unit = {
    +    val table = "tbl"
    +    withTable(table) {
    +      df.write.format("json").saveAsTable(table)
    +      val columns = expectedColStatsSeq.map(_._1)
    +      val columnStats = spark.sessionState.computeColumnStats(table, columns)
    --- End diff --
    
    Change this too.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    I looked at your test cases. Are there any one that actually depend on things in the Hive module? There is also an in-memory catalog for sql/core that you can use.
    
    In addition, unfortunately I think the current way is testing is too coupled with the internals of the catalog and too brittle. It is also a part that is being refactored pretty heavily. We definitely don't want changes to the metastore relation having to change the stats tests. Please think of a new way to have tests without depending on internals of other parts of the system.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79272492
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    --- End diff --
    
    I think this is an open question. IMO, as a computing framework like Spark, it is difficult to decide when to recollect the stats, because that depends on how often the data is changed and how it is changed, i.e. how customers use Spark. For different applications, this can be quite different. So I think maybe we should leave the decision to users or someone like DBAs who know their applications well, let them decide when to run the "ANALYZE" commands and refresh the stats.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80633172
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    --- End diff --
    
    nice!


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Could you add a positive test case when we turn on the case sensitivity? The scenario is like:
    ```
        withTable(table) {
          withSQLConf("spark.sql.caseSensitive" -> "true") {
            sql(s"CREATE TABLE $table (c1 int, C1 double) USING PARQUET")
            sql(s"INSERT INTO $table SELECT 1, 3.0")
            sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS c1, C1")
          }
        }
    ``` 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78790309
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -98,8 +98,12 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
           AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    -    } else {
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    @gatorsmile The tests for parsing analyze commands are in `StatisticsSuite`, so I'll add those verifying tests in it instead of `DDLCommandSuite`.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80161814
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
    --- End diff --
    
    I think it's ok for now, because we don't have other ways to see the column stats. We can delete this when we support `DESC FORMATTED TABLE COLUMN` command, which shows column-level stats (including histograms?) of the given column. 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66053/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79926080
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: NamedExpression, relativeSD: Double): CreateStruct = {
    +    // Use aggregate functions to compute statistics we need:
    +    // - number of nulls: Sum(If(IsNull(e), one, zero));
    +    // - maximum value: Max(e);
    +    // - minimum value: Min(e);
    +    // - ndv (number of distinct values): HyperLogLogPlusPlus(e, relativeSD);
    +    // - average length of values: Average(Length(e));
    +    // - maximum length of values: Max(Length(e));
    +    // - number of true values: Sum(If(e, one, zero));
    +    // - number of false values: Sum(If(Not(e), one, zero));
    +    // - If we don't need some statistic for the data type, use null literal.
    +    // Note that: the order of each sequence must be as follows:
    +    // numNulls, max, min, ndv, avgColLen, maxColLen, numTrues, numFalses
    +    var statistics = e.dataType match {
    +      case _: NumericType | TimestampType | DateType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    --- End diff --
    
    Yeah, I think we should do that, thanks.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79496929
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    --- End diff --
    
    Agree. Just do not forget to add a test case for it.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79275019
  
    --- Diff: sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveExternalCatalog.scala ---
    @@ -401,7 +401,10 @@ private[spark] class HiveExternalCatalog(conf: SparkConf, hadoopConf: Configurat
           var statsProperties: Map[String, String] =
             Map(STATISTICS_TOTAL_SIZE -> stats.sizeInBytes.toString())
           if (stats.rowCount.isDefined) {
    -        statsProperties += (STATISTICS_NUM_ROWS -> stats.rowCount.get.toString())
    +        statsProperties += STATISTICS_NUM_ROWS -> stats.rowCount.get.toString()
    --- End diff --
    
    Yes, we just give it a different name in Spark.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78687777
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -98,8 +98,12 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
           AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    -    } else {
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    Then, issue an exception here. 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80628790
  
    --- Diff: sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/UnsafeRow.java ---
    @@ -31,6 +31,7 @@
     import com.esotericsoftware.kryo.io.Input;
     import com.esotericsoftware.kryo.io.Output;
     
    +import org.apache.spark.sql.catalyst.plans.logical.Except;
    --- End diff --
    
    unnecessary change


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81668637
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala ---
    @@ -581,6 +581,13 @@ object SQLConf {
           .timeConf(TimeUnit.MILLISECONDS)
           .createWithDefault(10L)
     
    +  val NDV_MAX_ERROR =
    +    SQLConfigBuilder("spark.sql.statistics.ndv.maxError")
    +      .internal()
    +      .doc("The maximum estimation error allowed in HyperLogLog++ algorithm.")
    --- End diff --
    
    > The maximum estimation error allowed in HyperLogLog++ algorithm.
    
    I mean, it sounds like this config is a general one to set the error for HyperLogLog++ algorithm in ALL scenarios.
    



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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78974439
  
    --- 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,
    --- End diff --
    
    Looks like `AnalyzeTableCommand` is also using String instead of `TableIdentifier`. Want to change as well?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66188/
    Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66227 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66227/consoleFull)** for PR 15090 at commit [`734abad`](https://github.com/apache/spark/commit/734abad045a5378d14489a4e956b7a8e1c95a811).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65349 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65349/consoleFull)** for PR 15090 at commit [`027bdcc`](https://github.com/apache/spark/commit/027bdcc59b1b01a8dac436dd3a86600c2451c95f).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65754/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79331978
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    Because the check here for estimated ndv value is not really related to the actual ndv value, we can't make sure if we really get the estimated ndv back. Especially we only use `ndv > 0` to check it. In an extreme case, we can replace the ndv expression with a literal(0) in the aggregation, the test would not check it out.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81450056
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,341 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val tableName = "tbl"
    +
    +    // we need to specify column names
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +
    +    val analyzeSql = s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS key, value"
    +    val parsed = spark.sessionState.sqlParser.parsePlan(analyzeSql)
    +    val expected = AnalyzeColumnCommand(TableIdentifier(tableName), Seq("key", "value"))
    +    comparePlans(parsed, expected)
    +  }
    +
    +  test("analyzing columns of non-atomic types is not supported") {
    +    val tableName = "tbl"
    +    withTable(tableName) {
    +      Seq(ArrayData(Seq(1, 2, 3), Seq(Seq(1, 2, 3)))).toDF().write.saveAsTable(tableName)
    +      val err = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS data")
    +      }
    +      assert(err.message.contains("Analyzing columns is not supported"))
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table ($colName1 int, `$colName2` string) USING PARQUET")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == "Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${colName1.toUpperCase}")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ${colName1.toUpperCase}.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val columnsToAnalyze = Seq(colName2.toUpperCase, colName1, colName2)
    +        val tableIdent = TableIdentifier(table, Some("default"))
    +        val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +        val columnStats =
    +          AnalyzeColumnCommand(tableIdent, columnsToAnalyze).computeColStats(spark, relation)._2
    +        assert(columnStats.contains(colName1))
    +        assert(columnStats.contains(colName2))
    +        // check deduplication
    +        assert(columnStats.size == 2)
    +        assert(!columnStats.contains(colName2.toUpperCase))
    +      }
    +    }
    +  }
    +
    +  private def getNonNullValues[T](values: Seq[Option[T]]): Seq[T] = {
    +    values.filter(_.isDefined).map(_.get)
    +  }
    +
    +  test("column-level statistics for integral type columns") {
    +    val values = (0 to 5).map { i =>
    +      if (i % 2 == 0) None else Some(i)
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toByte), i.map(_.toShort), i.map(_.toInt), i.map(_.toLong))
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3", "c4")
    +    val nonNullValues = getNonNullValues[Int](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.max,
    +        nonNullValues.min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for fractional type columns") {
    +    val values: Seq[Option[Decimal]] = (0 to 5).map { i =>
    +      if (i == 0) None else Some(Decimal(i + i * 0.01))
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toFloat), i.map(_.toDouble), i)
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3")
    +    val nonNullValues = getNonNullValues[Decimal](values)
    +    val numNulls = values.count(_.isEmpty).toLong
    +    val ndv = nonNullValues.distinct.length.toLong
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = f.dataType match {
    +        case floatType: FloatType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max.toFloat, nonNullValues.min.toFloat,
    +            ndv))
    +        case doubleType: DoubleType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max.toDouble, nonNullValues.min.toDouble,
    +            ndv))
    +        case decimalType: DecimalType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max, nonNullValues.min, ndv))
    +      }
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for string column") {
    +    val values = Seq(None, Some("a"), Some("bbbb"), Some("cccc"), Some(""))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[String](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.map(_.length).sum / nonNullValues.length.toDouble,
    +        nonNullValues.map(_.length).max.toLong,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for binary column") {
    +    val values = Seq(None, Some("a"), Some("bbbb"), Some("cccc"), Some("")).map(_.map(_.getBytes))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Array[Byte]](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.map(_.length).sum / nonNullValues.length.toDouble,
    +        nonNullValues.map(_.length).max.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for boolean column") {
    +    val values = Seq(None, Some(true), Some(false), Some(true))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Boolean](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.count(_.equals(true)).toLong,
    +        nonNullValues.count(_.equals(false)).toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for date column") {
    +    val values = Seq(None, Some("1970-01-01"), Some("1970-02-02")).map(_.map(Date.valueOf))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Date](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        // Internally, DateType is represented as the number of days from 1970-01-01.
    +        nonNullValues.map(DateTimeUtils.fromJavaDate).max,
    +        nonNullValues.map(DateTimeUtils.fromJavaDate).min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for timestamp column") {
    +    val values = Seq(None, Some("1970-01-01 00:00:00"), Some("1970-01-01 00:00:05")).map { i =>
    +      i.map(Timestamp.valueOf)
    +    }
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Timestamp](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        // Internally, TimestampType is represented as the number of days from 1970-01-01
    +        nonNullValues.map(DateTimeUtils.fromJavaTimestamp).max,
    +        nonNullValues.map(DateTimeUtils.fromJavaTimestamp).min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for null columns") {
    +    val values = Seq(None, None)
    +    val data = values.map { i =>
    +      (i.map(_.toString), i.map(_.toString.toInt))
    +    }
    +    val df = data.toDF("c1", "c2")
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      (f, ColumnStat(InternalRow(values.count(_.isEmpty).toLong, null, null, 0L)))
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for columns with different types") {
    +    val intSeq = Seq(1, 2)
    +    val doubleSeq = Seq(1.01d, 2.02d)
    +    val stringSeq = Seq("a", "bb")
    +    val binarySeq = Seq("a", "bb").map(_.getBytes)
    +    val booleanSeq = Seq(true, false)
    +    val dateSeq = Seq("1970-01-01", "1970-02-02").map(Date.valueOf)
    +    val timestampSeq = Seq("1970-01-01 00:00:00", "1970-01-01 00:00:05").map(Timestamp.valueOf)
    +    val longSeq = Seq(5L, 4L)
    +
    +    val data = intSeq.indices.map { i =>
    +      (intSeq(i), doubleSeq(i), stringSeq(i), binarySeq(i), booleanSeq(i), dateSeq(i),
    +        timestampSeq(i), longSeq(i))
    +    }
    +    val df = data.toDF("c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8")
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = f.dataType match {
    +        case IntegerType =>
    +          ColumnStat(InternalRow(0L, intSeq.max, intSeq.min, intSeq.distinct.length.toLong))
    +        case DoubleType =>
    +          ColumnStat(InternalRow(0L, doubleSeq.max, doubleSeq.min,
    +              doubleSeq.distinct.length.toLong))
    +        case StringType =>
    +          ColumnStat(InternalRow(0L, stringSeq.map(_.length).sum / stringSeq.length.toDouble,
    +                stringSeq.map(_.length).max.toLong, stringSeq.distinct.length.toLong))
    +        case BinaryType =>
    +          ColumnStat(InternalRow(0L, binarySeq.map(_.length).sum / binarySeq.length.toDouble,
    +                binarySeq.map(_.length).max.toLong))
    +        case BooleanType =>
    +          ColumnStat(InternalRow(0L, booleanSeq.count(_.equals(true)).toLong,
    +              booleanSeq.count(_.equals(false)).toLong))
    +        case DateType =>
    +          ColumnStat(InternalRow(0L, dateSeq.map(DateTimeUtils.fromJavaDate).max,
    +                dateSeq.map(DateTimeUtils.fromJavaDate).min, dateSeq.distinct.length.toLong))
    +        case TimestampType =>
    +          ColumnStat(InternalRow(0L, timestampSeq.map(DateTimeUtils.fromJavaTimestamp).max,
    +                timestampSeq.map(DateTimeUtils.fromJavaTimestamp).min,
    +                timestampSeq.distinct.length.toLong))
    +        case LongType =>
    +          ColumnStat(InternalRow(0L, longSeq.max, longSeq.min, longSeq.distinct.length.toLong))
    +      }
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("update table-level stats while collecting column-level stats") {
    +    val table = "tbl"
    +    val tmpTable = "tmp"
    +    withTable(table, tmpTable) {
    +      val values = Seq(1)
    +      val df = values.toDF("c1")
    +      df.write.format("json").saveAsTable(tmpTable)
    +
    +      sql(s"CREATE TABLE $table (c1 int) USING PARQUET")
    +      sql(s"INSERT INTO $table SELECT * FROM $tmpTable")
    --- End diff --
    
    we can just write `INSERT INTO $table SELECT 1`, thus don't need the temp table


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66131 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66131/consoleFull)** for PR 15090 at commit [`3335af6`](https://github.com/apache/spark/commit/3335af65c2b53dcfa96bf1f5602043cf3d11e3b1).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65810 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65810/consoleFull)** for PR 15090 at commit [`bb19f72`](https://github.com/apache/spark/commit/bb19f72789abc960efb937712512c0716fecd800).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81456177
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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.TableIdentifier
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val duplicatedColumns = mutable.MutableList[String]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      } else {
    +        duplicatedColumns += col
    +      }
    +    }
    +    if (duplicatedColumns.nonEmpty) {
    +      logWarning(s"Duplicated columns ${duplicatedColumns.mkString("(", ", ", ")")} detected " +
    +        s"when analyzing columns ${columnNames.mkString("(", ", ", ")")}, ignoring them.")
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      val numFields = ColumnStatStruct.numStatFields(expr.dataType)
    +      (expr.name, ColumnStat(statsRow.getStruct(i + 1, numFields)))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = {
    +    // the approximate ndv should never be larger than the number of rows
    +    Least(Seq(HyperLogLogPlusPlus(e, relativeSD), Count(one)))
    +  }
    +  def avgLength(e: Expression): Expression = Average(Length(e))
    +  def maxLength(e: Expression): Expression = Max(Length(e))
    +  def numTrues(e: Expression): Expression = Sum(If(e, one, zero))
    +  def numFalses(e: Expression): Expression = Sum(If(Not(e), one, zero))
    +
    +  def getStruct(exprs: Seq[Expression]): CreateStruct = {
    +    CreateStruct(exprs.map { expr: Expression =>
    +      expr.transformUp {
    +        case af: AggregateFunction => af.toAggregateExpression()
    +      }
    +    })
    +  }
    +
    +  def numericColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), max(e), min(e), ndv(e, relativeSD))
    +  }
    +
    +  def stringColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e), ndv(e, relativeSD))
    +  }
    +
    +  def binaryColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e))
    +  }
    +
    +  def booleanColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), numTrues(e), numFalses(e))
    +  }
    +
    +  def numStatFields(dataType: DataType): Int = {
    +    dataType match {
    +      case BinaryType | BooleanType => 3
    +      case _ => 4
    +    }
    +  }
    +
    +  def apply(e: Attribute, relativeSD: Double): CreateStruct = e.dataType match {
    --- End diff --
    
    Nit: `e` -> `attr`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79543159
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,343 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.AnalysisException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStats
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[AnalysisException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val quotedColumn = "x.yz"
    +    val quotedName = s"`$quotedColumn`"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table (abc int, $quotedName string)")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == s"Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ABC")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ABC.")
    --- End diff --
    
    A useless `s`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79546259
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,168 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    --- End diff --
    
    This is a bug. `tableIdent` might not have `database`. We need to qualify it. There are a couple of ways to do it.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    What's "basic" about? Are we going to have something that's not basic in the future (e.g. histogram)? If yes, should those go into a separate class or just in ColumnStats?



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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79925464
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    +    min: Option[Any] = None,
    +    ndv: Option[Long] = None,
    +    avgColLen: Option[Double] = None,
    +    maxColLen: Option[Long] = None,
    +    numTrues: Option[Long] = None,
    +    numFalses: Option[Long] = None) {
    +
    +  override def toString: String = "ColumnStats(" + simpleString + ")"
    +
    +  def simpleString: String = {
    +    Seq(s"numNulls=$numNulls",
    +      if (max.isDefined) s"max=${max.get}" else "",
    +      if (min.isDefined) s"min=${min.get}" else "",
    +      if (ndv.isDefined) s"ndv=${ndv.get}" else "",
    +      if (avgColLen.isDefined) s"avgColLen=${avgColLen.get}" else "",
    +      if (maxColLen.isDefined) s"maxColLen=${maxColLen.get}" else "",
    +      if (numTrues.isDefined) s"numTrues=${numTrues.get}" else "",
    +      if (numFalses.isDefined) s"numFalses=${numFalses.get}" else ""
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +object ColumnStats {
    +  def fromString(str: String, dataType: DataType): ColumnStats = {
    --- End diff --
    
    ok


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79330943
  
    --- 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 = {
    --- End diff --
    
    Then we will need to pass many parameters to this method.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    A SQL function. : ) I might underestimate the effort. 
    
    Like what @hvanhovell said, how about adding a test suite in sql/core for verifying  [`updateStats `](https://github.com/wzhfy/spark/blob/392a312dd3dd606d6cfa9f96af246d718fc0fb42/sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala#L74-L99)? ( @wzhfy , `alterTable` and `refreshTable` are not needed to test. Maybe you can separate them from `updateStats`)


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79327748
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    It should be:
    
    1. estimate column statistics for several times.
    2. calculate mean and standard deviation of ndv for the multiple statistics.
    3. check if the real ndv value is within (mean + 3 * sd, mean - 3 * sd).
    
    Please correct me if it is wrong.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66226 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66226/consoleFull)** for PR 15090 at commit [`734abad`](https://github.com/apache/spark/commit/734abad045a5378d14489a4e956b7a8e1c95a811).
     * This patch **fails MiMa tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    The test suite `StatisticsColumnSuite` misses the negative cases. For example, so far, we do not allow users to analyze the temporary tables. 
    
    Ideally, all the exceptions the code could issue need a test case. 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79161115
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    --- End diff --
    
    Why not user a more functional approach, and use `map` here? That saves adding elements by hand, and creating the list in the first place.
    
    You can also deduplicate the columns here.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79159036
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val two = Literal(2, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: Expression, relativeSD: Double): CreateStruct = {
    +    var statistics = e.dataType match {
    +      case n: NumericType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    +          nullLong)
    +      case TimestampType | DateType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    +          nullLong)
    +      case StringType =>
    +        Seq(nullString, nullString, HyperLogLogPlusPlus(e, relativeSD), Average(Length(e)),
    +          Max(Length(e)), nullLong, nullLong)
    +      case BinaryType =>
    +        Seq(nullBinary, nullBinary, nullLong, Average(Length(e)), Max(Length(e)), nullLong,
    +          nullLong)
    +      case BooleanType =>
    +        Seq(nullBoolean, nullBoolean, two, nullDouble, nullLong, Sum(If(e, one, zero)),
    +          Sum(If(e, zero, one)))
    +      case otherType =>
    +        throw new AnalysisException("ANALYZE command is not supported for data type: " +
    --- End diff --
    
    This can be a bit clearer for the end user. Please add the name of the column & mention that you are analyzing columns.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66227 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66227/consoleFull)** for PR 15090 at commit [`734abad`](https://github.com/apache/spark/commit/734abad045a5378d14489a4e956b7a8e1c95a811).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79965425
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,352 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStats
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    def assertAnalyzeColumnCommand(analyzeCommand: String, c: Class[_]) {
    +      val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +      val operators = parsed.collect {
    +        case a: AnalyzeColumnCommand => a
    +        case o => o
    +      }
    +      assert(operators.size == 1)
    +      if (operators.head.getClass != c) {
    +        fail(
    +          s"""$analyzeCommand expected command: $c, but got ${operators.head}
    +             |parsed command:
    +             |$parsed
    +           """.stripMargin)
    +      }
    +    }
    +
    +    val table = "table"
    +    assertAnalyzeColumnCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    val quotedColName2 = s"`$colName2`"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table ($colName1 int, $quotedColName2 string) USING PARQUET")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == "Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${colName1.toUpperCase}")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ${colName1.toUpperCase}.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val columnsToAnalyze = Seq(colName2.toUpperCase, colName1, colName2)
    +        val columnStats = spark.sessionState.computeColumnStats(table, columnsToAnalyze)
    --- End diff --
    
    Here, you can just replace it by 
    ```Scala
            val tableIdent = TableIdentifier(table, Option("default"))
            val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
            val columnStats =
              AnalyzeColumnCommand(tableIdent, columnsToAnalyze).computeColStats(spark, relation)._2
    ```


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65793 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65793/consoleFull)** for PR 15090 at commit [`b43115c`](https://github.com/apache/spark/commit/b43115cba3c818b08d8e0b576bf4d088dcfebd5e).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65793/
    Test FAILed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65935 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65935/consoleFull)** for PR 15090 at commit [`2b64549`](https://github.com/apache/spark/commit/2b645496e8965730690b5e72ea0f589371f9e9d7).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `case class ColumnStat(dataType: DataType, statRow: InternalRow) `
      * `case class NumericColumnStat[T <: AtomicType](statRow: InternalRow, dataType: T) `
      * `case class StringColumnStat(statRow: InternalRow) `
      * `case class BinaryColumnStat(statRow: InternalRow) `
      * `case class BooleanColumnStat(statRow: InternalRow) `


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65749 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65749/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78685262
  
    --- 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)
    --- End diff --
    
    Please consider case sensitivity here.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65633/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79335325
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,228 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.{AnalysisException, Row}
    +import org.apache.spark.sql.catalyst.plans.logical.BasicColStats
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    val noColumnError = intercept[AnalysisException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +    assert(noColumnError.message == "Need to specify the columns to analyze. Usage: " +
    +      "ANALYZE TABLE tbl COMPUTE STATISTICS FOR COLUMNS key, value")
    +
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table (key INT, value STRING)")
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS k")
    +      }
    +      assert(invalidColError.message == s"Invalid column name: k")
    +
    +      val duplicateColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, key")
    +      }
    +      assert(duplicateColError.message == s"Duplicate column name: key")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS keY")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: keY")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val duplicateErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, vaLue")
    +        }
    +        assert(duplicateErr.message == s"Duplicate column name: vaLue")
    +      }
    +    }
    +  }
    +
    +  test("basic statistics for integral type columns") {
    +    val rdd = sparkContext.parallelize(Seq("1", null, "2", "3", null)).map { i =>
    +      if (i != null) Row(i.toByte, i.toShort, i.toInt, i.toLong) else Row(i, i, i, i)
    --- End diff --
    
    @wzhfy I guess he understood `"1", null, "2", "3", null` are the actual values for rows. Could we maybe make this easier to read? How about the codes below?
    
    ```scala
    val values = (0 to 5).map { i =>
      if (i % 2 == 0) None else Some(i)
    }
    val data = values.map { i =>
      (i.map(_.toByte), i.map(_.toShort), i.map(_.toInt), i.map(_.toLong))
    }
    
    val df = data.toDF("c1", "c2", "c3", "c4")
    val statsSeq = df.schema.map { f =>
      val basicStats = BasicColStats(
        dataType = f.dataType,
        numNulls = values.count(_.isDefined),
        max = values.filter(_.isDefined).max,
        min = values.filter(_.isDefined).min,
        ndv = Some(values.distinct.length.toLong))
      (f.name, basicStats)
    }
    
    checkColStats(df, statsSeq)
    ```
    
    with importing  `import testImplicits._` right below `StatisticsColumnSuite` and then changing `checkColStats`
    
    as below:
    
    ```scala
    def checkColStats(
        df: DataFrame,
        expectedColStatsSeq: Seq[(String, BasicColStats)]): Unit = {
      val table = "tbl"
      withTable(table) {
        df.write.format("json").saveAsTable(table)
        val columns = expectedColStatsSeq.map(_._1).mkString(", ")
        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS $columns")
        val readback = sql(s"SELECT * FROM $table")
        val stats = readback.queryExecution.analyzed.collect {
          case rel: LogicalRelation =>
            expectedColStatsSeq.foreach { expected =>
              assert(rel.catalogTable.get.stats.get.basicColStats.contains(expected._1))
              checkColStats(colStats = rel.catalogTable.get.stats.get.basicColStats(expected._1),
                expectedColStats = expected._2)
            }
        }
        assert(stats.size == 1)
      }
    }
    ```


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65793 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65793/consoleFull)** for PR 15090 at commit [`b43115c`](https://github.com/apache/spark/commit/b43115cba3c818b08d8e0b576bf4d088dcfebd5e).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80629224
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,27 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    +   * Create an [[AnalyzeTableCommand]] command or an [[AnalyzeColumnCommand]] command.
    +   * Example SQL for analyzing table :
        * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    +   *   ANALYZE TABLE table COMPUTE STATISTICS [NOSCAN];
    +   * }}}
    +   * Example SQL for analyzing columns :
    +   * {{{
    +   *   ANALYZE TABLE table COMPUTE STATISTICS FOR COLUMNS column1, column2;
        * }}}
        */
       override def visitAnalyze(ctx: AnalyzeContext): LogicalPlan = withOrigin(ctx) {
         if (ctx.partitionSpec == null &&
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
    -      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    +      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier))
    +    } else if (ctx.identifierSeq() == null) {
    +      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier), noscan = false)
    --- End diff --
    
    when will we hit this branch?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78685116
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -98,8 +98,12 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
           AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    -    } else {
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    This has a bug. It will jump to this branch, if users input 
    ```SQL
    ANALYZE TABLE t1 COMPUTE STATISTICS FOR COLUMNS
    ```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79767198
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSourceStrategy.scala ---
    @@ -209,16 +212,17 @@ class FindDataSourceTable(sparkSession: SparkSession) extends Rule[LogicalPlan]
     
         LogicalRelation(
           dataSource.resolveRelation(),
    +      expectedOutputAttributes = Some(simpleCatalogRelation.output),
    --- End diff --
    
    Yeah, I'm doing this, I'll submit it tomorrow:)


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79491476
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    --- End diff --
    
    I am just not to sure that we should follow an all or nothing collection approach. Currently `ANALYZE TABLE` discards column level statistics and `ANALYSE COLUMN` discards statistics on any column that has not been included in the given analyze command.
    
    In the databases I have worked with you could typically refresh columns stats independently. I would be a big proponent of doing so.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81192204
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,355 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    --- End diff --
    
    I follow the style in StatisticsSuite. I think this style is ok.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66131 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66131/consoleFull)** for PR 15090 at commit [`3335af6`](https://github.com/apache/spark/commit/3335af65c2b53dcfa96bf1f5602043cf3d11e3b1).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66150 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66150/consoleFull)** for PR 15090 at commit [`06819dd`](https://github.com/apache/spark/commit/06819ddbfae6fad8056ca6e8293692c22856fb95).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80629937
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    --- End diff --
    
    why do we need to refresh table for statistics updating? AFAIK, refresh table is used when the table data files changed, and we need to list files again and invalidate table cache.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80763362
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = {
    +    val approxNdv = HyperLogLogPlusPlus(e, relativeSD)
    +    // the approximate ndv should not be larger than the number of rows
    +    If(LessThanOrEqual(approxNdv, Count(one)), approxNdv, Count(one))
    --- End diff --
    
    That's much better! Thanks!


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #66226 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/66226/consoleFull)** for PR 15090 at commit [`734abad`](https://github.com/apache/spark/commit/734abad045a5378d14489a4e956b7a8e1c95a811).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79547634
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,168 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    --- End diff --
    
    This is a design decision. Should we output the outcomes of this command? cc @hvanhovell 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65994/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79544029
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,343 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.AnalysisException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStats
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[AnalysisException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val quotedColumn = "x.yz"
    +    val quotedName = s"`$quotedColumn`"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table (abc int, $quotedName string)")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == s"Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ABC")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ABC.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${quotedName.toUpperCase}, " +
    +          s"ABC, $quotedName")
    +        val df = sql(s"SELECT * FROM $table")
    +        val stats = df.queryExecution.analyzed.collect {
    +          case rel: MetastoreRelation =>
    +            val colStats = rel.catalogTable.stats.get.colStats
    +            // check deduplication
    +            assert(colStats.size == 2)
    +            assert(colStats.contains(quotedColumn))
    +            assert(colStats.contains("abc"))
    +        }
    +        assert(stats.size == 1)
    +      }
    +    }
    +  }
    +
    +  private def getNonNullValues[T](values: Seq[Option[T]]): Seq[T] = {
    +    values.filter(_.isDefined).map(_.get)
    +  }
    +
    +  test("column-level statistics for integral type columns") {
    +    val values = (0 to 5).map { i =>
    +      if (i % 2 == 0) None else Some(i)
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toByte), i.map(_.toShort), i.map(_.toInt), i.map(_.toLong))
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3", "c4")
    +    val nonNullValues = getNonNullValues[Int](values)
    +    val statsSeq = df.schema.map { f =>
    +      val colStats = ColumnStats(
    +        dataType = f.dataType,
    +        numNulls = values.count(_.isEmpty),
    +        max = Some(nonNullValues.max),
    +        min = Some(nonNullValues.min),
    +        ndv = Some(nonNullValues.distinct.length.toLong))
    +      (f.name, colStats)
    +    }
    +    checkColStats(df, statsSeq)
    +  }
    +
    +  test("column-level statistics for fractional type columns") {
    +    val values = (0 to 5).map { i =>
    +      if (i == 0) None else Some(i + i * 0.01d)
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toFloat), i.map(_.toDouble), i.map(Decimal(_)))
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3")
    +    val nonNullValues = getNonNullValues[Double](values)
    +    val statsSeq = df.schema.map { f =>
    +      val colStats = ColumnStats(
    +        dataType = f.dataType,
    +        numNulls = values.count(_.isEmpty),
    +        max = Some(nonNullValues.max),
    +        min = Some(nonNullValues.min),
    +        ndv = Some(nonNullValues.distinct.length.toLong))
    +      (f.name, colStats)
    +    }
    +    checkColStats(df, statsSeq)
    +  }
    +
    +  test("column-level statistics for string column") {
    +    val values = Seq(None, Some("a"), Some("bbbb"), Some("cccc"))
    --- End diff --
    
    Please also add an empty string.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    @gatorsmile OK, I'll rebase and add some tests to handle negative cases.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81460994
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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.TableIdentifier
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val duplicatedColumns = mutable.MutableList[String]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      } else {
    +        duplicatedColumns += col
    +      }
    +    }
    +    if (duplicatedColumns.nonEmpty) {
    +      logWarning(s"Duplicated columns ${duplicatedColumns.mkString("(", ", ", ")")} detected " +
    +        s"when analyzing columns ${columnNames.mkString("(", ", ", ")")}, ignoring them.")
    --- End diff --
    
    How about this?
    ```Scala
          logWarning("A duplicate column name was detected in `ANALYZE TABLE` statement. " +
            s"Input columns: ${columnNames.mkString("(", ", ", ")")}. " +
            s"Duplicate columns: ${duplicatedColumns.mkString("(", ", ", ")")}.")
    ```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78983110
  
    --- 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 = {
    --- End diff --
    
    private?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65347 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65347/consoleFull)** for PR 15090 at commit [`59ae3df`](https://github.com/apache/spark/commit/59ae3dfc45751705962a1370c195c67c6302c376).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    The latest update includes the following changes:
    1. move the test suite for column stats into sql/core;
    2. extract the computing logic in `AnalyzeColumnCommand` as a separate method;
    3. add an api for testing in `SessionState`: `computeColumnStats()`, so that we can get the stats result directly by calling this api and compare it with the expected result in our test cases , without depending on the catalog module.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80761163
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = {
    +    val approxNdv = HyperLogLogPlusPlus(e, relativeSD)
    +    // the approximate ndv should not be larger than the number of rows
    +    If(LessThanOrEqual(approxNdv, Count(one)), approxNdv, Count(one))
    --- End diff --
    
    Nit: Use `Least` expression. That should be quicker, and should be (of course) less code :)


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80615261
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,179 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = HyperLogLogPlusPlus(e, relativeSD)
    +  def avgLength(e: Expression): Expression = Average(Length(e))
    +  def maxLength(e: Expression): Expression = Max(Length(e))
    +  def numTrues(e: Expression): Expression = Sum(If(e, one, zero))
    +  def numFalses(e: Expression): Expression = Sum(If(Not(e), one, zero))
    +
    +  def getStruct(exprs: Seq[Expression]): CreateStruct = {
    +    CreateStruct(exprs.map {
    +      case af: AggregateFunction => af.toAggregateExpression()
    +      case e: Expression => e
    +    })
    +  }
    +
    +  def numericColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), max(e), min(e), ndv(e, relativeSD))
    +  }
    +
    +  def stringColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e), ndv(e, relativeSD))
    +  }
    +
    +  def binaryColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e))
    +  }
    +
    +  def booleanColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), numTrues(e), numFalses(e))
    +  }
    +
    +  def apply(e: Attribute, relativeSD: Double): CreateStruct = e.dataType match {
    +    // Use aggregate functions to compute statistics we need.
    +    case _: NumericType | TimestampType | DateType => getStruct(numericColumnStat(e, relativeSD))
    +    case StringType => getStruct(stringColumnStat(e, relativeSD))
    +    case BinaryType => getStruct(binaryColumnStat(e))
    +    case BooleanType => getStruct(booleanColumnStat(e))
    +    case otherType =>
    +      throw new AnalysisException("Analyzing columns is not supported for column " +
    +        s"${e.name} of data type: ${e.dataType}.")
    +  }
    +
    +  def unwrapStruct(
    +      row: InternalRow,
    +      offset: Int,
    +      e: Expression,
    +      relativeSD: Double,
    +      rowCount: Long): ColumnStat = {
    +    val numFields = e.dataType match {
    +      case _: NumericType | TimestampType | DateType => numericColumnStat(e, relativeSD).length
    +      case StringType => stringColumnStat(e, relativeSD).length
    +      case BinaryType => binaryColumnStat(e).length
    +      case BooleanType => booleanColumnStat(e).length
    +    }
    +    val struct = row.getStruct(offset, numFields)
    +    // NumericType, TimestampType, DateType and StringType have ndv and its index is 3.
    +    if (numFields >= 4 && !struct.isNullAt(3)) {
    +      // ndv should not be larger than number of rows
    +      if (struct.getLong(3) > rowCount) struct.asInstanceOf[UnsafeRow].setLong(3, rowCount)
    --- End diff --
    
    Please move this into the `ndv` expression itself. Use the `MinOf` expression.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78718313
  
    --- 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
    --- End diff --
    
    why call to RDD here?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79296634
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,23 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    -   * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    -   * }}}
    +   * Create an [[AnalyzeTableCommand]] command or an [[AnalyzeColumnCommand]] command.
        */
       override def visitAnalyze(ctx: AnalyzeContext): LogicalPlan = withOrigin(ctx) {
         if (ctx.partitionSpec == null &&
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
    -      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    +      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier))
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    Yeah, good idea


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79161012
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    --- End diff --
    
    To me it is not a problem when a user a specifies the same columns twice. Lets just deduplicate this.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80638681
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SessionState.scala ---
    @@ -186,13 +187,18 @@ private[sql] class SessionState(sparkSession: SparkSession) {
       }
     
       /**
    -   * Analyzes the given table in the current database to generate statistics, which will be
    +   * Analyzes the given table in the current database to generate table-level statistics, which
    +   * will be used in query optimizations.
    +   */
    +  def analyzeTable(tableIdent: TableIdentifier, noscan: Boolean = true): Unit = {
    +    AnalyzeTableCommand(tableIdent, noscan).run(sparkSession)
    +  }
    +
    +  /**
    +   * Analyzes the given columns in the table to generate column-level statistics, which will be
        * used in query optimizations.
    -   *
    -   * Right now, it only supports catalog tables and it only updates the size of a catalog table
    -   * in the external catalog.
        */
    -  def analyze(tableName: String, noscan: Boolean = true): Unit = {
    --- End diff --
    
    actually this method is never used....
    
    We should keep it unchanged in this PR, and remove it in follow-up


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79547296
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,168 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: NamedExpression, relativeSD: Double): CreateStruct = {
    --- End diff --
    
    Could you add a clear description about this struct, esepcially the definition of each field?  


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78685328
  
    --- 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)}
    --- End diff --
    
    Also verify whether the list contains duplicate columns.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79968621
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,352 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStats
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    def assertAnalyzeColumnCommand(analyzeCommand: String, c: Class[_]) {
    +      val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +      val operators = parsed.collect {
    +        case a: AnalyzeColumnCommand => a
    +        case o => o
    +      }
    +      assert(operators.size == 1)
    +      if (operators.head.getClass != c) {
    +        fail(
    +          s"""$analyzeCommand expected command: $c, but got ${operators.head}
    +             |parsed command:
    +             |$parsed
    +           """.stripMargin)
    +      }
    +    }
    +
    +    val table = "table"
    +    assertAnalyzeColumnCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    val quotedColName2 = s"`$colName2`"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table ($colName1 int, $quotedColName2 string) USING PARQUET")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == "Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${colName1.toUpperCase}")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ${colName1.toUpperCase}.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val columnsToAnalyze = Seq(colName2.toUpperCase, colName1, colName2)
    +        val columnStats = spark.sessionState.computeColumnStats(table, columnsToAnalyze)
    --- End diff --
    
    Thanks!


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66226/
    Test FAILed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81450027
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,341 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val tableName = "tbl"
    +
    +    // we need to specify column names
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +
    +    val analyzeSql = s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS key, value"
    +    val parsed = spark.sessionState.sqlParser.parsePlan(analyzeSql)
    +    val expected = AnalyzeColumnCommand(TableIdentifier(tableName), Seq("key", "value"))
    +    comparePlans(parsed, expected)
    +  }
    +
    +  test("analyzing columns of non-atomic types is not supported") {
    +    val tableName = "tbl"
    +    withTable(tableName) {
    +      Seq(ArrayData(Seq(1, 2, 3), Seq(Seq(1, 2, 3)))).toDF().write.saveAsTable(tableName)
    +      val err = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS data")
    +      }
    +      assert(err.message.contains("Analyzing columns is not supported"))
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table ($colName1 int, `$colName2` string) USING PARQUET")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == "Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${colName1.toUpperCase}")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ${colName1.toUpperCase}.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val columnsToAnalyze = Seq(colName2.toUpperCase, colName1, colName2)
    +        val tableIdent = TableIdentifier(table, Some("default"))
    +        val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +        val columnStats =
    +          AnalyzeColumnCommand(tableIdent, columnsToAnalyze).computeColStats(spark, relation)._2
    +        assert(columnStats.contains(colName1))
    +        assert(columnStats.contains(colName2))
    +        // check deduplication
    +        assert(columnStats.size == 2)
    +        assert(!columnStats.contains(colName2.toUpperCase))
    +      }
    +    }
    +  }
    +
    +  private def getNonNullValues[T](values: Seq[Option[T]]): Seq[T] = {
    +    values.filter(_.isDefined).map(_.get)
    +  }
    +
    +  test("column-level statistics for integral type columns") {
    +    val values = (0 to 5).map { i =>
    +      if (i % 2 == 0) None else Some(i)
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toByte), i.map(_.toShort), i.map(_.toInt), i.map(_.toLong))
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3", "c4")
    +    val nonNullValues = getNonNullValues[Int](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.max,
    +        nonNullValues.min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for fractional type columns") {
    +    val values: Seq[Option[Decimal]] = (0 to 5).map { i =>
    +      if (i == 0) None else Some(Decimal(i + i * 0.01))
    +    }
    +    val data = values.map { i =>
    +      (i.map(_.toFloat), i.map(_.toDouble), i)
    +    }
    +
    +    val df = data.toDF("c1", "c2", "c3")
    +    val nonNullValues = getNonNullValues[Decimal](values)
    +    val numNulls = values.count(_.isEmpty).toLong
    +    val ndv = nonNullValues.distinct.length.toLong
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = f.dataType match {
    +        case floatType: FloatType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max.toFloat, nonNullValues.min.toFloat,
    +            ndv))
    +        case doubleType: DoubleType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max.toDouble, nonNullValues.min.toDouble,
    +            ndv))
    +        case decimalType: DecimalType =>
    +          ColumnStat(InternalRow(numNulls, nonNullValues.max, nonNullValues.min, ndv))
    +      }
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for string column") {
    +    val values = Seq(None, Some("a"), Some("bbbb"), Some("cccc"), Some(""))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[String](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.map(_.length).sum / nonNullValues.length.toDouble,
    +        nonNullValues.map(_.length).max.toLong,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for binary column") {
    +    val values = Seq(None, Some("a"), Some("bbbb"), Some("cccc"), Some("")).map(_.map(_.getBytes))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Array[Byte]](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.map(_.length).sum / nonNullValues.length.toDouble,
    +        nonNullValues.map(_.length).max.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for boolean column") {
    +    val values = Seq(None, Some(true), Some(false), Some(true))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Boolean](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        nonNullValues.count(_.equals(true)).toLong,
    +        nonNullValues.count(_.equals(false)).toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for date column") {
    +    val values = Seq(None, Some("1970-01-01"), Some("1970-02-02")).map(_.map(Date.valueOf))
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Date](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        // Internally, DateType is represented as the number of days from 1970-01-01.
    +        nonNullValues.map(DateTimeUtils.fromJavaDate).max,
    +        nonNullValues.map(DateTimeUtils.fromJavaDate).min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for timestamp column") {
    +    val values = Seq(None, Some("1970-01-01 00:00:00"), Some("1970-01-01 00:00:05")).map { i =>
    +      i.map(Timestamp.valueOf)
    +    }
    +    val df = values.toDF("c1")
    +    val nonNullValues = getNonNullValues[Timestamp](values)
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = ColumnStat(InternalRow(
    +        values.count(_.isEmpty).toLong,
    +        // Internally, TimestampType is represented as the number of days from 1970-01-01
    +        nonNullValues.map(DateTimeUtils.fromJavaTimestamp).max,
    +        nonNullValues.map(DateTimeUtils.fromJavaTimestamp).min,
    +        nonNullValues.distinct.length.toLong))
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for null columns") {
    +    val values = Seq(None, None)
    +    val data = values.map { i =>
    +      (i.map(_.toString), i.map(_.toString.toInt))
    +    }
    +    val df = data.toDF("c1", "c2")
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      (f, ColumnStat(InternalRow(values.count(_.isEmpty).toLong, null, null, 0L)))
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("column-level statistics for columns with different types") {
    +    val intSeq = Seq(1, 2)
    +    val doubleSeq = Seq(1.01d, 2.02d)
    +    val stringSeq = Seq("a", "bb")
    +    val binarySeq = Seq("a", "bb").map(_.getBytes)
    +    val booleanSeq = Seq(true, false)
    +    val dateSeq = Seq("1970-01-01", "1970-02-02").map(Date.valueOf)
    +    val timestampSeq = Seq("1970-01-01 00:00:00", "1970-01-01 00:00:05").map(Timestamp.valueOf)
    +    val longSeq = Seq(5L, 4L)
    +
    +    val data = intSeq.indices.map { i =>
    +      (intSeq(i), doubleSeq(i), stringSeq(i), binarySeq(i), booleanSeq(i), dateSeq(i),
    +        timestampSeq(i), longSeq(i))
    +    }
    +    val df = data.toDF("c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8")
    +    val expectedColStatsSeq = df.schema.map { f =>
    +      val colStat = f.dataType match {
    +        case IntegerType =>
    +          ColumnStat(InternalRow(0L, intSeq.max, intSeq.min, intSeq.distinct.length.toLong))
    +        case DoubleType =>
    +          ColumnStat(InternalRow(0L, doubleSeq.max, doubleSeq.min,
    +              doubleSeq.distinct.length.toLong))
    +        case StringType =>
    +          ColumnStat(InternalRow(0L, stringSeq.map(_.length).sum / stringSeq.length.toDouble,
    +                stringSeq.map(_.length).max.toLong, stringSeq.distinct.length.toLong))
    +        case BinaryType =>
    +          ColumnStat(InternalRow(0L, binarySeq.map(_.length).sum / binarySeq.length.toDouble,
    +                binarySeq.map(_.length).max.toLong))
    +        case BooleanType =>
    +          ColumnStat(InternalRow(0L, booleanSeq.count(_.equals(true)).toLong,
    +              booleanSeq.count(_.equals(false)).toLong))
    +        case DateType =>
    +          ColumnStat(InternalRow(0L, dateSeq.map(DateTimeUtils.fromJavaDate).max,
    +                dateSeq.map(DateTimeUtils.fromJavaDate).min, dateSeq.distinct.length.toLong))
    +        case TimestampType =>
    +          ColumnStat(InternalRow(0L, timestampSeq.map(DateTimeUtils.fromJavaTimestamp).max,
    +                timestampSeq.map(DateTimeUtils.fromJavaTimestamp).min,
    +                timestampSeq.distinct.length.toLong))
    +        case LongType =>
    +          ColumnStat(InternalRow(0L, longSeq.max, longSeq.min, longSeq.distinct.length.toLong))
    +      }
    +      (f, colStat)
    +    }
    +    checkColStats(df, expectedColStatsSeq)
    +  }
    +
    +  test("update table-level stats while collecting column-level stats") {
    +    val table = "tbl"
    +    val tmpTable = "tmp"
    +    withTable(table, tmpTable) {
    +      val values = Seq(1)
    +      val df = values.toDF("c1")
    +      df.write.format("json").saveAsTable(tmpTable)
    +
    +      sql(s"CREATE TABLE $table (c1 int) USING PARQUET")
    +      sql(s"INSERT INTO $table SELECT * FROM $tmpTable")
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS")
    +      checkTableStats(tableName = table, expectedRowCount = Some(values.length))
    +
    +      // update table-level stats between analyze table and analyze column commands
    +      sql(s"INSERT INTO $table SELECT * FROM $tmpTable")
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS c1")
    +      val fetchedStats =
    +        checkTableStats(tableName = table, expectedRowCount = Some(values.length * 2))
    +
    +      val colStat = fetchedStats.get.colStats("c1")
    +      StatisticsTest.checkColStat(
    +        dataType = IntegerType,
    +        colStat = colStat,
    +        expectedColStat = ColumnStat(InternalRow.fromSeq(
    +          Seq(0L, values.max, values.min, values.distinct.length.toLong))),
    --- End diff --
    
    I think we should write `InternalRow(0L, values.max, ...)` directly


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    This pr has been updated based on all the above comments, changes are as follows:
    1. Modify analyze syntax a little bit: `identifierSeq` is now non-optional, i.e. users must specify column names after `FOR COLUMNS`.
    2. Check column correctness based on case sensitivity.
    3. Deduplicate columns when checking correctness.
    4. Support analyzing columns independently, i.e. when analyzing new columns, now we don\u2019t remove stats of columns which are analyzed before.
    5. Rename `BasicColStats` to `ColumnStats`.
    6. Use 3*standard deviation to check ndv result in test cases.
    7. Code refactoring based on comments.



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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Like Hive, I think we should implement a built-in function, `compute_stats`. Then, the implementation of `AnalyzeColumnCommand` will be much cleaner.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80097979
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,189 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStats]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    --- End diff --
    
    @gatorsmile There's no need to handle case sensitivity here, because in `attributesToAnalyze` we have the name in schema. For example, if the column name in schema is "abc", for columns "abc" and "ABC", both their name in expr are "abc".


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81243645
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    --- End diff --
    
    Good advice! Thanks.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80629335
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table in the current database to generate statistics,
    --- End diff --
    
    `... in the current database ...` users can specify the database in table name right? I think we can just say `given table`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78981349
  
    --- 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
    --- End diff --
    
    If we can trust the `nullable` of attributes, can we skip calculating the number of null for the attribute which is not nullable.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    In this PR, we use `ColumnStats` to represent the column statistics in memory, and persist in to hive metastore by converting it to string with format `a=1,b=2`. This brings 2 problems:
    
    1. `ColumnStats` always contains all the fields, which means a int column also has the `numTrues` property, although it's None
    2. it's unefficient to convert `ColumnStats` to string in format `a=1,b=2` and parse it back.
    
    My suggestion:
    We can just use `InternalRow` to represent the column statistics in memory. The schema of this `InternalRow` is defined as contract, e.g. for int column, the schema is `<max: int, min: int, ndv: long, ...>`.
    When persist it to hive metastore, we first serialize the row to binary(we can use `UnsafeRow`, then the serializaiton is free), and then covert bianry to hex string(or use other encodings).
    
    This can solve the 2 problems, what do you think?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    I would argue strongly against creating a single aggregate function to calculate all statistics, for a couple of reasons:
    
    1. This would create a tonne of duplicated code (integrating HLL+ nicely will be a pain).
    2. These functions have all been tested.
    
    I do like the idea of testing the actual collection of column statistics separately from the analyze columns command.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81102018
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    --- End diff --
    
    we only need the struct numFields here right? Can we follow what we did in `ColumnStat`?
    ```
    val numFields = dataType match {
           case BinaryType | BooleanType => 3
           case _ => 4
         }
    ```
    
    then we don't need unwrapStruct


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78718154
  
    --- 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("*")))
    --- End diff --
    
    IMO constructing the `LogicalPlan` directly makes more sense here.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78684701
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -98,8 +98,12 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
           AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    -    } else {
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    Since this PR changes the Parser, please update the comment of this function to reflect the latest changes. 
    
    In addition, please add the test cases in `DDLCommandSuite` for verifying the Parser's behaviors


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Another test case for Unicode column names in ANALYZE COLUMN:
    
    ```Scala
        // scalastyle:off
        // non ascii characters are not allowed in the source code, so we disable the scalastyle.
        val colName1 = "`\u52171`"
        val colName2 = "`\u52172`"
        // scalastyle:on
        withTable(table) {
          sql(s"CREATE TABLE $table ($colName1 int, $colName2 double) USING PARQUET")
          sql(s"INSERT INTO $table SELECT 1, 3.0")
          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS $colName2, $colName1")
          ...
        }```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79975372
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,189 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStats]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    --- End diff --
    
    Deduplication lacks case sensitivity handling. 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79329639
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    Why 3 standard deviations? I think for tests in this suite, we just need to make sure we get the stats, we should leave the accuracy test to HyperLogLogPlusPlusSuite, right?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81453552
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,170 @@
    +/*
    + * 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.TableIdentifier
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      } else {
    +        logWarning(s"Duplicated column: $col")
    --- End diff --
    
    You need to explain the context. Otherwise, the log message becomes useless. 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65749 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65749/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65941 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65941/consoleFull)** for PR 15090 at commit [`08df669`](https://github.com/apache/spark/commit/08df66937d8834c8e0b7300beea1973705f852b7).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    @wzhfy  You also fixed a bug in this PR. Could you create a separate PR? Then, we can backport it easily if needed. Sometimes, if you fix a bug in a huge PR like this, we might be hard to investigate the impacts of your fix. Thanks!


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78732371
  
    --- 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))
    --- End diff --
    
    use flatmap?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81379672
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    --- End diff --
    
    @gatorsmile OK, let me add a log for it.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79975005
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsTest.scala ---
    @@ -0,0 +1,93 @@
    +/*
    + * 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
    +
    +import org.apache.spark.sql.catalyst.TableIdentifier
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with SharedSQLContext {
    +
    +  def checkColStats(
    +      df: DataFrame,
    +      expectedColStatsSeq: Seq[(String, ColumnStats)]): Unit = {
    +    val table = "tbl"
    +    withTable(table) {
    +      df.write.format("json").saveAsTable(table)
    +      val columns = expectedColStatsSeq.map(_._1)
    +      val tableIdent = TableIdentifier(table, Some("default"))
    +      val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +      val columnStats =
    +        AnalyzeColumnCommand(tableIdent, columns).computeColStats(spark, relation)._2
    +      expectedColStatsSeq.foreach { expected =>
    +        assert(columnStats.contains(expected._1))
    +        checkColStats(colStats = columnStats(expected._1), expectedColStats = expected._2)
    +      }
    +    }
    +  }
    +
    +  def checkColStats(colStats: ColumnStats, expectedColStats: ColumnStats): Unit = {
    +    assert(colStats.dataType == expectedColStats.dataType)
    +    assert(colStats.numNulls == expectedColStats.numNulls)
    +    colStats.dataType match {
    +      case _: IntegralType | DateType | TimestampType =>
    +        assert(colStats.max.map(_.toString.toLong) == expectedColStats.max.map(_.toString.toLong))
    +        assert(colStats.min.map(_.toString.toLong) == expectedColStats.min.map(_.toString.toLong))
    +      case _: FractionalType =>
    +        assert(colStats.max.map(_.toString.toDouble) == expectedColStats
    +          .max.map(_.toString.toDouble))
    +        assert(colStats.min.map(_.toString.toDouble) == expectedColStats
    +          .min.map(_.toString.toDouble))
    +      case _ =>
    +        // other types don't have max and min stats
    +        assert(colStats.max.isEmpty)
    +        assert(colStats.min.isEmpty)
    +    }
    +    colStats.dataType match {
    +      case BinaryType | BooleanType => assert(colStats.ndv.isEmpty)
    +      case _ =>
    +        // ndv is an approximate value, so we make sure we have the value, and it should be
    +        // within 3*SD's of the given rsd.
    +        assert(colStats.ndv.get >= 0)
    +        if (expectedColStats.ndv.get == 0) {
    +          assert(colStats.ndv.get == 0)
    +        } else if (expectedColStats.ndv.get > 0) {
    +          val rsd = spark.sessionState.conf.ndvMaxError
    +          val error = math.abs((colStats.ndv.get / expectedColStats.ndv.get.toDouble) - 1.0d)
    +          assert(error <= rsd * 3.0d, "Error should be within 3 std. errors.")
    +        }
    +    }
    +    assert(colStats.avgColLen == expectedColStats.avgColLen)
    +    assert(colStats.maxColLen == expectedColStats.maxColLen)
    +    assert(colStats.numTrues == expectedColStats.numTrues)
    +    assert(colStats.numFalses == expectedColStats.numFalses)
    +  }
    +
    +  def checkTableStats(tableName: String, expectedRowCount: Option[Int]): Option[Statistics] = {
    +    val df = sql(s"SELECT * FROM $tableName")
    --- End diff --
    
    ```Scala
    val df = spark.table(tableName)
    ```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78731287
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,70 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param basicColStats Basic column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    basicColStats: Map[String, BasicColStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (basicColStats.nonEmpty) s"basicColStats=$basicColStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +case class BasicColStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    --- End diff --
    
    This has the potential of becoming a very large value (if you use some complex structure). Do we want this? 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Alright looking at the number of outstanding comments, it looks like none of the issues are structural anymore. I'm going to merge this in order to speed up this work. @wzhfy please make sure you fix the remaining issues in follow-up pull requests.
    
    Merging into master.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66150/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81259064
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +38,84 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStat] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + */
    +case class ColumnStat(statRow: InternalRow) {
    +
    +  def forNumeric[T <: AtomicType](dataType: T): NumericColumnStat[T] = {
    +    NumericColumnStat(statRow, dataType)
    +  }
    +  def forString: StringColumnStat = StringColumnStat(statRow)
    +  def forBinary: BinaryColumnStat = BinaryColumnStat(statRow)
    +  def forBoolean: BooleanColumnStat = BooleanColumnStat(statRow)
    +
    +  override def toString: String = {
    +    // use Base64 for encoding
    +    Base64.encodeBase64String(statRow.asInstanceOf[UnsafeRow].getBytes)
       }
     }
    +
    +object ColumnStat {
    +  def apply(dataType: DataType, str: String): ColumnStat = {
    +    // use Base64 for decoding
    +    val bytes = Base64.decodeBase64(str)
    +    val numFields = dataType match {
    +      case BinaryType | BooleanType => 3
    +      case _ => 4
    +    }
    +    val unsafeRow = new UnsafeRow(numFields)
    --- End diff --
    
    ah i see, sorry I read the code wrong


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81454093
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,341 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val tableName = "tbl"
    +
    +    // we need to specify column names
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +
    +    val analyzeSql = s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS key, value"
    +    val parsed = spark.sessionState.sqlParser.parsePlan(analyzeSql)
    +    val expected = AnalyzeColumnCommand(TableIdentifier(tableName), Seq("key", "value"))
    +    comparePlans(parsed, expected)
    +  }
    +
    +  test("analyzing columns of non-atomic types is not supported") {
    +    val tableName = "tbl"
    +    withTable(tableName) {
    +      Seq(ArrayData(Seq(1, 2, 3), Seq(Seq(1, 2, 3)))).toDF().write.saveAsTable(tableName)
    +      val err = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS data")
    +      }
    +      assert(err.message.contains("Analyzing columns is not supported"))
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table ($colName1 int, `$colName2` string) USING PARQUET")
    +
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key")
    +      }
    +      assert(invalidColError.message == "Invalid column name: key.")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS ${colName1.toUpperCase}")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: ${colName1.toUpperCase}.")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val columnsToAnalyze = Seq(colName2.toUpperCase, colName1, colName2)
    +        val tableIdent = TableIdentifier(table, Some("default"))
    +        val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +        val columnStats =
    +          AnalyzeColumnCommand(tableIdent, columnsToAnalyze).computeColStats(spark, relation)._2
    --- End diff --
    
    The same here. 


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65935 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65935/consoleFull)** for PR 15090 at commit [`2b64549`](https://github.com/apache/spark/commit/2b645496e8965730690b5e72ea0f589371f9e9d7).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79161613
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    --- End diff --
    
    Lets move these two lines into the `ColumStatsStruct` object. 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79974658
  
    --- Diff: sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveExternalCatalog.scala ---
    @@ -473,15 +476,20 @@ private[spark] class HiveExternalCatalog(conf: SparkConf, hadoopConf: Configurat
           }
         }
         // construct Spark's statistics from information in Hive metastore
    -    if (catalogTable.properties.contains(STATISTICS_TOTAL_SIZE)) {
    -      val totalSize = BigInt(catalogTable.properties.get(STATISTICS_TOTAL_SIZE).get)
    -      // TODO: we will compute "estimatedSize" when we have column stats:
    -      // average size of row * number of rows
    +    if (catalogTable.properties.filterKeys(_.startsWith(STATISTICS_PREFIX)).nonEmpty) {
    +      val colStatsProps = catalogTable.properties
    +        .filterKeys(_.startsWith(STATISTICS_BASIC_COL_STATS_PREFIX))
    +        .map { case (k, v) => (k.replace(STATISTICS_BASIC_COL_STATS_PREFIX, ""), v)}
    --- End diff --
    
    Add a space between `)` and `}`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79015892
  
    --- 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 = {
    --- End diff --
    
    It's in def run.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81453676
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsTest.scala ---
    @@ -0,0 +1,129 @@
    +/*
    + * 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
    +
    +import org.apache.spark.sql.catalyst.TableIdentifier
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics}
    +import org.apache.spark.sql.execution.command.{AnalyzeColumnCommand, ColumnStatStruct}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with SharedSQLContext {
    +
    +  def checkColStats(
    +      df: DataFrame,
    +      expectedColStatsSeq: Seq[(StructField, ColumnStat)]): Unit = {
    +    val table = "tbl"
    +    withTable(table) {
    +      df.write.format("json").saveAsTable(table)
    +      val columns = expectedColStatsSeq.map(_._1)
    +      val tableIdent = TableIdentifier(table, Some("default"))
    +      val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +      val columnStats =
    +        AnalyzeColumnCommand(tableIdent, columns.map(_.name)).computeColStats(spark, relation)._2
    +      expectedColStatsSeq.foreach { expected =>
    --- End diff --
    
    Yeah, that's better.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79521372
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,228 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.{AnalysisException, Row}
    +import org.apache.spark.sql.catalyst.plans.logical.BasicColStats
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    val noColumnError = intercept[AnalysisException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +    assert(noColumnError.message == "Need to specify the columns to analyze. Usage: " +
    +      "ANALYZE TABLE tbl COMPUTE STATISTICS FOR COLUMNS key, value")
    +
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table (key INT, value STRING)")
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS k")
    +      }
    +      assert(invalidColError.message == s"Invalid column name: k")
    +
    +      val duplicateColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, key")
    +      }
    +      assert(duplicateColError.message == s"Duplicate column name: key")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS keY")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: keY")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val duplicateErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, vaLue")
    +        }
    +        assert(duplicateErr.message == s"Duplicate column name: vaLue")
    +      }
    +    }
    +  }
    +
    +  test("basic statistics for integral type columns") {
    +    val rdd = sparkContext.parallelize(Seq("1", null, "2", "3", null)).map { i =>
    +      if (i != null) Row(i.toByte, i.toShort, i.toInt, i.toLong) else Row(i, i, i, i)
    --- End diff --
    
    Cool, please add some salt to this when you fix (as I don't think mine is perfect anyway :)).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81455841
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,175 @@
    +/*
    + * 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.TableIdentifier
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.types._
    +
    +
    +/**
    + * Analyzes the given columns of the given table to generate statistics, which will be used in
    + * query optimizations.
    + */
    +case class AnalyzeColumnCommand(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val duplicatedColumns = mutable.MutableList[String]()
    +    val resolver = sparkSession.sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find(attr => resolver(attr.name, col))
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      } else {
    +        duplicatedColumns += col
    +      }
    +    }
    +    if (duplicatedColumns.nonEmpty) {
    +      logWarning(s"Duplicated columns ${duplicatedColumns.mkString("(", ", ", ")")} detected " +
    +        s"when analyzing columns ${columnNames.mkString("(", ", ", ")")}, ignoring them.")
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      val numFields = ColumnStatStruct.numStatFields(expr.dataType)
    +      (expr.name, ColumnStat(statsRow.getStruct(i + 1, numFields)))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = {
    +    // the approximate ndv should never be larger than the number of rows
    +    Least(Seq(HyperLogLogPlusPlus(e, relativeSD), Count(one)))
    +  }
    +  def avgLength(e: Expression): Expression = Average(Length(e))
    +  def maxLength(e: Expression): Expression = Max(Length(e))
    +  def numTrues(e: Expression): Expression = Sum(If(e, one, zero))
    +  def numFalses(e: Expression): Expression = Sum(If(Not(e), one, zero))
    +
    +  def getStruct(exprs: Seq[Expression]): CreateStruct = {
    --- End diff --
    
    All the above functions should be private, right?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78734109
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeTableCommand.scala ---
    @@ -129,3 +87,51 @@ case class AnalyzeTableCommand(tableName: String, noscan: Boolean = true) extend
         Seq.empty[Row]
       }
     }
    +
    +object AnalyzeTableCommand extends Logging {
    --- End diff --
    
    nvm I got it.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65994 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65994/consoleFull)** for PR 15090 at commit [`377a491`](https://github.com/apache/spark/commit/377a4919f43f6da86f1dd7c0d121d0436d377431).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    LGTM except some minor comment, thanks for working on it!


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81449665
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsTest.scala ---
    @@ -0,0 +1,129 @@
    +/*
    + * 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
    +
    +import org.apache.spark.sql.catalyst.TableIdentifier
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, Statistics}
    +import org.apache.spark.sql.execution.command.{AnalyzeColumnCommand, ColumnStatStruct}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.test.SharedSQLContext
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with SharedSQLContext {
    +
    +  def checkColStats(
    +      df: DataFrame,
    +      expectedColStatsSeq: Seq[(StructField, ColumnStat)]): Unit = {
    +    val table = "tbl"
    +    withTable(table) {
    +      df.write.format("json").saveAsTable(table)
    +      val columns = expectedColStatsSeq.map(_._1)
    +      val tableIdent = TableIdentifier(table, Some("default"))
    +      val relation = spark.sessionState.catalog.lookupRelation(tableIdent)
    +      val columnStats =
    +        AnalyzeColumnCommand(tableIdent, columns.map(_.name)).computeColStats(spark, relation)._2
    +      expectedColStatsSeq.foreach { expected =>
    --- End diff --
    
    how about `...foreach { case (field, expectedStat) =>` ? Then we use `field.name` instead of `expected._1.name`.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79542607
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,19 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    -   * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    -   * }}}
    --- End diff --
    
    Any reason why you removed it? Since this is out-dated, you just need to update it. 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79329962
  
    --- 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 = {
    --- End diff --
    
    Can this be then defined outside? I know this is about personal taste but it causes confusion to at least two of reviewers here.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79766998
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/DataSourceStrategy.scala ---
    @@ -209,16 +212,17 @@ class FindDataSourceTable(sparkSession: SparkSession) extends Rule[LogicalPlan]
     
         LogicalRelation(
           dataSource.resolveRelation(),
    +      expectedOutputAttributes = Some(simpleCatalogRelation.output),
    --- End diff --
    
    Could you create a separate PR for this bug fix?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    retest this please


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79492145
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    --- End diff --
    
    Ok, that makes sense. You could also use the resolved attribute's name as a key to store the stats. @gatorsmile does hive store column names in a case sensitive way? I thought that we always convert them to lower case?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81453655
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +38,80 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStat] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + */
    +case class ColumnStat(statRow: InternalRow) {
    +
    +  def forNumeric[T <: AtomicType](dataType: T): NumericColumnStat[T] = {
    --- End diff --
    
    But we need to include DateType and TimestampType.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79332105
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    Of course my previous suggestion `0 <= ndv <= count(col)` is also failed for this standard. Using sd to check it is more reliable. I am not strong against this. But it should be better. See what @hvanhovell and @cloud-fan think?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79897549
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,182 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    --- End diff --
    
    I think catalyst.resolver gives you a comparator based on the conf. Might be cleaner to just use that


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79705637
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,19 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    -   * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    -   * }}}
    --- End diff --
    
    @gatorsmile This was a limitation explaining that we only supported analyze table with NOSCAN, now we don't have this limitation.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81507325
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala ---
    @@ -581,6 +581,13 @@ object SQLConf {
           .timeConf(TimeUnit.MILLISECONDS)
           .createWithDefault(10L)
     
    +  val NDV_MAX_ERROR =
    +    SQLConfigBuilder("spark.sql.statistics.ndv.maxError")
    +      .internal()
    +      .doc("The maximum estimation error allowed in HyperLogLog++ algorithm.")
    --- End diff --
    
    This config comment is not correct. It looks like it will set up the maximum estimation error for HyperLogLog++ algorithm.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78686975
  
    --- 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)
    --- End diff --
    
    key and KeY are different columns?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79326407
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    --- End diff --
    
    @hvanhovell Do you mean using `relation.resolve(UnresolvedAttribute.parseAttributeName(col), resolver)`? In this case, \`a.d\` will be split into `a` and `d`, because after parsing, \`a.d\` will become a.d in analyze command. I think `relation.resolve(Seq(col), resolver)` is ok, right?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79924979
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    --- End diff --
    
    Yes, but do we have a primitive numeric type is scala?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Yes we can keep stats of other columns, but we can't be sure if they are still correct between two analyze column commands, unless we recollect them. It's again the consistency issue, like between analyze table and analyze column.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78973782
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,70 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param basicColStats Basic column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    basicColStats: Map[String, BasicColStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (basicColStats.nonEmpty) s"basicColStats=$basicColStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +case class BasicColStats(
    +    dataType: DataType,
    +    numNulls: Long,
    --- End diff --
    
    Any reason why `numNulls` is the only one not wrapped in `Option` here?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80626981
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,179 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = HyperLogLogPlusPlus(e, relativeSD)
    +  def avgLength(e: Expression): Expression = Average(Length(e))
    +  def maxLength(e: Expression): Expression = Max(Length(e))
    +  def numTrues(e: Expression): Expression = Sum(If(e, one, zero))
    +  def numFalses(e: Expression): Expression = Sum(If(Not(e), one, zero))
    +
    +  def getStruct(exprs: Seq[Expression]): CreateStruct = {
    +    CreateStruct(exprs.map {
    +      case af: AggregateFunction => af.toAggregateExpression()
    +      case e: Expression => e
    +    })
    +  }
    +
    +  def numericColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), max(e), min(e), ndv(e, relativeSD))
    +  }
    +
    +  def stringColumnStat(e: Expression, relativeSD: Double): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e), ndv(e, relativeSD))
    +  }
    +
    +  def binaryColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), avgLength(e), maxLength(e))
    +  }
    +
    +  def booleanColumnStat(e: Expression): Seq[Expression] = {
    +    Seq(numNulls(e), numTrues(e), numFalses(e))
    +  }
    +
    +  def apply(e: Attribute, relativeSD: Double): CreateStruct = e.dataType match {
    +    // Use aggregate functions to compute statistics we need.
    +    case _: NumericType | TimestampType | DateType => getStruct(numericColumnStat(e, relativeSD))
    +    case StringType => getStruct(stringColumnStat(e, relativeSD))
    +    case BinaryType => getStruct(binaryColumnStat(e))
    +    case BooleanType => getStruct(booleanColumnStat(e))
    +    case otherType =>
    +      throw new AnalysisException("Analyzing columns is not supported for column " +
    +        s"${e.name} of data type: ${e.dataType}.")
    +  }
    +
    +  def unwrapStruct(
    +      row: InternalRow,
    +      offset: Int,
    +      e: Expression,
    +      relativeSD: Double,
    +      rowCount: Long): ColumnStat = {
    +    val numFields = e.dataType match {
    +      case _: NumericType | TimestampType | DateType => numericColumnStat(e, relativeSD).length
    +      case StringType => stringColumnStat(e, relativeSD).length
    +      case BinaryType => binaryColumnStat(e).length
    +      case BooleanType => booleanColumnStat(e).length
    +    }
    +    val struct = row.getStruct(offset, numFields)
    +    // NumericType, TimestampType, DateType and StringType have ndv and its index is 3.
    +    if (numFields >= 4 && !struct.isNullAt(3)) {
    +      // ndv should not be larger than number of rows
    +      if (struct.getLong(3) > rowCount) struct.asInstanceOf[UnsafeRow].setLong(3, rowCount)
    --- End diff --
    
    ok, thanks!


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65347 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65347/consoleFull)** for PR 15090 at commit [`59ae3df`](https://github.com/apache/spark/commit/59ae3dfc45751705962a1370c195c67c6302c376).
     * This patch **fails Scala style tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `case class BasicColStats(`
      * `case class AnalyzeColumnCommand(`
      * `trait StatsAggFunc `


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78683972
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsSuite.scala ---
    @@ -330,14 +332,237 @@ class StatisticsSuite extends QueryTest with TestHiveSingleton with SQLTestUtils
           val dfNoCols = spark.createDataFrame(rddNoCols, StructType(Seq.empty))
           dfNoCols.write.format("json").saveAsTable(table_no_cols)
           sql(s"ANALYZE TABLE $table_no_cols COMPUTE STATISTICS")
    -      checkStats(
    +      checkTableStats(
             table_no_cols,
             isDataSourceTable = true,
             hasSizeInBytes = true,
             expectedRowCounts = Some(10))
         }
       }
     
    +  private def checkColStats(
    --- End diff --
    
    This test suite becomes bigger and bigger. For column stats, let us create a new file?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79161379
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    --- End diff --
    
    `exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col")) is shorter`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79159302
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +}
    +
    +object ColumnStatsStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +  val two = Literal(2, LongType)
    +  val nullLong = Literal(null, LongType)
    +  val nullDouble = Literal(null, DoubleType)
    +  val nullString = Literal(null, StringType)
    +  val nullBinary = Literal(null, BinaryType)
    +  val nullBoolean = Literal(null, BooleanType)
    +  val statsNumber = 8
    +
    +  def apply(e: Expression, relativeSD: Double): CreateStruct = {
    +    var statistics = e.dataType match {
    +      case n: NumericType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    +          nullLong)
    +      case TimestampType | DateType =>
    +        Seq(Max(e), Min(e), HyperLogLogPlusPlus(e, relativeSD), nullDouble, nullLong, nullLong,
    +          nullLong)
    +      case StringType =>
    +        Seq(nullString, nullString, HyperLogLogPlusPlus(e, relativeSD), Average(Length(e)),
    +          Max(Length(e)), nullLong, nullLong)
    +      case BinaryType =>
    +        Seq(nullBinary, nullBinary, nullLong, Average(Length(e)), Max(Length(e)), nullLong,
    +          nullLong)
    +      case BooleanType =>
    +        Seq(nullBoolean, nullBoolean, two, nullDouble, nullLong, Sum(If(e, one, zero)),
    +          Sum(If(e, zero, one)))
    +      case otherType =>
    +        throw new AnalysisException("ANALYZE command is not supported for data type: " +
    +          s"${e.dataType}")
    +    }
    +    statistics = if (e.nullable) {
    +      Sum(If(IsNull(e), one, zero)) +: statistics
    +    } else {
    +      zero +: statistics
    +    }
    +    assert(statistics.length == statsNumber)
    +    CreateStruct(statistics.map {
    +      case af: AggregateFunction => af.toAggregateExpression()
    +      case e: Expression => e
    +    })
    +  }
    +
    +  def unwrapRow(e: Expression, row: InternalRow): BasicColStats = {
    +    BasicColStats(
    +      dataType = e.dataType,
    +      numNulls = row.getLong(0),
    +      max = if (row.isNullAt(1)) None else Some(row.get(1, e.dataType)),
    --- End diff --
    
    It might be nicer to add a helper method here.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65810 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65810/consoleFull)** for PR 15090 at commit [`bb19f72`](https://github.com/apache/spark/commit/bb19f72789abc960efb937712512c0716fecd800).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65477 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65477/consoleFull)** for PR 15090 at commit [`9cdc722`](https://github.com/apache/spark/commit/9cdc722780445c62ed2c306ede0ebc4829dbdbe8).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65475 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65475/consoleFull)** for PR 15090 at commit [`761a9e0`](https://github.com/apache/spark/commit/761a9e0641ac6e6f4798d4be988ded0875b974a0).


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80638078
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +      .queryExecution.toRdd.collect().head
    +
    +    // unwrap the result
    +    val rowCount = statsRow.getLong(0)
    +    val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +      (expr.name, ColumnStatStruct.unwrapStruct(statsRow, i + 1, expr, ndvMaxErr, rowCount))
    +    }.toMap
    +    (rowCount, columnStats)
    +  }
    +}
    +
    +object ColumnStatStruct {
    +  val zero = Literal(0, LongType)
    +  val one = Literal(1, LongType)
    +
    +  def numNulls(e: Expression): Expression = if (e.nullable) Sum(If(IsNull(e), one, zero)) else zero
    +  def max(e: Expression): Expression = Max(e)
    +  def min(e: Expression): Expression = Min(e)
    +  def ndv(e: Expression, relativeSD: Double): Expression = {
    +    val approxNdv = HyperLogLogPlusPlus(e, relativeSD)
    +    // the approximate ndv should not be larger than the number of rows
    +    If(LessThanOrEqual(approxNdv, Count(one)), approxNdv, Count(one))
    +  }
    +  def avgLength(e: Expression): Expression = Average(Length(e))
    +  def maxLength(e: Expression): Expression = Max(Length(e))
    +  def numTrues(e: Expression): Expression = Sum(If(e, one, zero))
    +  def numFalses(e: Expression): Expression = Sum(If(Not(e), one, zero))
    +
    +  def getStruct(exprs: Seq[Expression]): CreateStruct = {
    +    CreateStruct(exprs.map { expr: Expression =>
    +      expr.transformUp {
    +        case af: AggregateFunction => af.toAggregateExpression()
    +        case e: Expression => e
    --- End diff --
    
    this case is unnecessary


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80629684
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -87,19 +87,27 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
       }
     
       /**
    -   * Create an [[AnalyzeTableCommand]] command. This currently only implements the NOSCAN
    -   * option (other options are passed on to Hive) e.g.:
    +   * Create an [[AnalyzeTableCommand]] command or an [[AnalyzeColumnCommand]] command.
    +   * Example SQL for analyzing table :
        * {{{
    -   *   ANALYZE TABLE table COMPUTE STATISTICS NOSCAN;
    +   *   ANALYZE TABLE table COMPUTE STATISTICS [NOSCAN];
    +   * }}}
    +   * Example SQL for analyzing columns :
    +   * {{{
    +   *   ANALYZE TABLE table COMPUTE STATISTICS FOR COLUMNS column1, column2;
        * }}}
        */
       override def visitAnalyze(ctx: AnalyzeContext): LogicalPlan = withOrigin(ctx) {
         if (ctx.partitionSpec == null &&
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
    -      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    +      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier))
    +    } else if (ctx.identifierSeq() == null) {
    +      AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier), noscan = false)
    --- End diff --
    
    analyze table without `noncan`


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65690/
    Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65477/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79502791
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    --- End diff --
    
    @hvanhovell Agree. If we want to support refresh column stats independently, we should do as @viirya said. But the consistency between the kept column stats and the refreshed column stats still needs to be guaranteed by users.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79543008
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,343 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.AnalysisException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStats
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[AnalysisException] {
    --- End diff --
    
    This is a `ParseException`, right?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80637650
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    +    }
    +
    +    Seq.empty[Row]
    +  }
    +
    +  def computeColStats(
    +      sparkSession: SparkSession,
    +      relation: LogicalPlan): (Long, Map[String, ColumnStat]) = {
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    // Collect statistics per column.
    +    // The first element in the result will be the overall row count, the following elements
    +    // will be structs containing all column stats.
    +    // The layout of each struct follows the layout of the ColumnStats.
    +    val ndvMaxErr = sparkSession.sessionState.conf.ndvMaxError
    +    val expressions = Count(Literal(1)).toAggregateExpression() +:
    +      attributesToAnalyze.map(ColumnStatStruct(_, ndvMaxErr))
    +    val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +    val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    --- End diff --
    
    what will happen if the table is empty?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65749/
    Test PASSed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78691097
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsSuite.scala ---
    @@ -330,14 +332,237 @@ class StatisticsSuite extends QueryTest with TestHiveSingleton with SQLTestUtils
           val dfNoCols = spark.createDataFrame(rddNoCols, StructType(Seq.empty))
           dfNoCols.write.format("json").saveAsTable(table_no_cols)
           sql(s"ANALYZE TABLE $table_no_cols COMPUTE STATISTICS")
    -      checkStats(
    +      checkTableStats(
             table_no_cols,
             isDataSourceTable = true,
             hasSizeInBytes = true,
             expectedRowCounts = Some(10))
         }
       }
     
    +  private def checkColStats(
    --- End diff --
    
    Maybe move these utility functions to `QueryTest`? I am not 100% sure whether this is the best home, but we definitely split this suite to smaller suites.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78718245
  
    --- 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: _*)
    --- End diff --
    
    Why call to RDD here?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79166182
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala ---
    @@ -563,6 +563,13 @@ object SQLConf {
           .timeConf(TimeUnit.MILLISECONDS)
           .createWithDefault(10L)
     
    +  val NDV_MAX_ERROR =
    +    SQLConfigBuilder("spark.sql.ndv.maxError")
    --- End diff --
    
    Could you place this under `spark.sql.statistics`?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/66227/
    Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    What do you mean by a built-in function? A SQL function, or just a normal Scala function? Sorry for asking because it is vague given the context we are in.



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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79296666
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    How to get the standard deviations?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78687294
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/SparkSqlParser.scala ---
    @@ -98,8 +98,12 @@ class SparkSqlAstBuilder(conf: SQLConf) extends AstBuilder {
           ctx.identifier != null &&
           ctx.identifier.getText.toLowerCase == "noscan") {
           AnalyzeTableCommand(visitTableIdentifier(ctx.tableIdentifier).toString)
    -    } else {
    +    } else if (ctx.identifierSeq() == null) {
    --- End diff --
    
    For analyze column command, users should know exactly what they want to do. So they need to specify the columns, otherwise, we don't compute statistics for columns. AFAIK, hive will generate all column stats for this case, but I think we should not do that. At least, we could provide other command like FOR ALL COLUMNS to do this.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79114194
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,159 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, BasicColStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val validColumns = mutable.MutableList[NamedExpression]()
    +    val resolver = sessionState.conf.resolver
    +    columnNames.foreach { col =>
    +      val exprOption = relation.resolve(col.split("\\."), resolver)
    +      if (exprOption.isEmpty) {
    +        throw new AnalysisException(s"Invalid column name: $col")
    +      }
    +      if (validColumns.map(_.exprId).contains(exprOption.get.exprId)) {
    +        throw new AnalysisException(s"Duplicate column name: $col")
    +      }
    +      validColumns += exprOption.get
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the BasicColStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        validColumns.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val colStats = validColumns.zipWithIndex.map { case (expr, i) =>
    +        val colInfo = statsRow.getStruct(i + 1, ColumnStatsStruct.statsNumber)
    +        val colStats = ColumnStatsStruct.unwrapRow(expr, colInfo)
    +        (expr.name, colStats)
    +      }.toMap
    +
    +      val statistics =
    +        Statistics(sizeInBytes = newTotalSize, rowCount = Some(rowCount), basicColStats = colStats)
    --- End diff --
    
    One question. Seems we overwrite all existing column statistics, no matter whether we collect statistics of other columns before. Is it better to only replace the column statistics of the same columns? We can keep the column statistics of other columns. @wzhfy What do you think?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79331568
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    What if the number of values is equal to ndv (e.g. primary key)? Can we expect the estimated mdv from HyperLogLogPlusPlus is always less than the accurate mdv?
    Besides, ndv can be equal to zero.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79893449
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    --- End diff --
    
    Shouldn't max/min be numeric ? (You're not planning on putting strings in here, right) ?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65475/
    Test FAILed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65633 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65633/consoleFull)** for PR 15090 at commit [`0f974c0`](https://github.com/apache/spark/commit/0f974c019401ac5cef1be1b1e69a523ee2287101).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65349 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65349/consoleFull)** for PR 15090 at commit [`027bdcc`](https://github.com/apache/spark/commit/027bdcc59b1b01a8dac436dd3a86600c2451c95f).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78687147
  
    --- 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)
    --- End diff --
    
    Yeah. In Spark, we have the SQLConf `spark.sql.caseSensitive` to control it.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79571121
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeTableCommand.scala ---
    @@ -129,3 +89,51 @@ case class AnalyzeTableCommand(tableName: String, noscan: Boolean = true) extend
         Seq.empty[Row]
       }
     }
    +
    +object AnalyzeTableCommand extends Logging {
    +
    +  def calculateTotalSize(sparkSession: SparkSession, catalogTable: CatalogTable): Long = {
    +    // This method is mainly based on
    +    // org.apache.hadoop.hive.ql.stats.StatsUtils.getFileSizeForTable(HiveConf, Table)
    +    // in Hive 0.13 (except that we do not use fs.getContentSummary).
    +    // TODO: Generalize statistics collection.
    +    // TODO: Why fs.getContentSummary returns wrong size on Jenkins?
    +    // Can we use fs.getContentSummary in future?
    +    // Seems fs.getContentSummary returns wrong table size on Jenkins. So we use
    +    // countFileSize to count the table size.
    +    val stagingDir =
    +    sparkSession.sessionState.conf.getConfString("hive.exec.stagingdir", ".hive-staging")
    --- End diff --
    
    FYI - there is an Indentation mistake here.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    I have a problem in converting between InternalRow  and String, as now we are using InternalRow to represent ColumnStat. 
    
    Since we want to persist ColumnStat into metastore and we use table parameters (a string to string map) to carry the stats, we need to encode ColumnStat to String when storing and decode ColumnStat from String when loading.
    
    Are there any APIs I can utilize? Or do I have to write something like a serializer?
    Any advices?


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65349/
    Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Do you still remember the test case I showed you in table-level statistics? A table with zero column. Can you add a test case for that scenario? 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81183194
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +38,84 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStat] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + */
    +case class ColumnStat(statRow: InternalRow) {
    +
    +  def forNumeric[T <: AtomicType](dataType: T): NumericColumnStat[T] = {
    +    NumericColumnStat(statRow, dataType)
    +  }
    +  def forString: StringColumnStat = StringColumnStat(statRow)
    +  def forBinary: BinaryColumnStat = BinaryColumnStat(statRow)
    +  def forBoolean: BooleanColumnStat = BooleanColumnStat(statRow)
    +
    +  override def toString: String = {
    +    // use Base64 for encoding
    +    Base64.encodeBase64String(statRow.asInstanceOf[UnsafeRow].getBytes)
       }
     }
    +
    +object ColumnStat {
    +  def apply(dataType: DataType, str: String): ColumnStat = {
    +    // use Base64 for decoding
    +    val bytes = Base64.decodeBase64(str)
    +    val numFields = dataType match {
    +      case BinaryType | BooleanType => 3
    +      case _ => 4
    +    }
    +    val unsafeRow = new UnsafeRow(numFields)
    --- End diff --
    
    it only returns an empty UnsafeRow:
    ```java
    row.pointTo(new byte[numBytes], numBytes);
    ```


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79441079
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsSuite.scala ---
    @@ -101,4 +101,47 @@ class StatisticsSuite extends QueryTest with SharedSQLContext {
           checkTableStats(tableName, expectedRowCount = Some(2))
         }
       }
    +
    +  test("test column-level statistics for data source table created in InMemoryCatalog") {
    +    def checkColStats(colStats: BasicColStats, expectedColStats: BasicColStats): Unit = {
    +      assert(colStats.dataType == expectedColStats.dataType)
    +      assert(colStats.numNulls == expectedColStats.numNulls)
    +      assert(colStats.max == expectedColStats.max)
    +      assert(colStats.min == expectedColStats.min)
    +      if (expectedColStats.ndv.isDefined) {
    +        // ndv is an approximate value, so we just make sure we have the value
    +        assert(colStats.ndv.get >= 0)
    --- End diff --
    
    I think I may know what @hvanhovell meant. The standard deviation is the parameter we pass to HyperLogLogPlusPlus, so the code may look like this:
    ```
            // ndv is an approximate value, so we make sure we have the value, and it should be
            // within 3*SD's of the given rsd.
            assert(colStats.ndv.get >= 0)
            val rsd = spark.sessionState.conf.ndvMaxError
            val error = math.abs((colStats.ndv.get / expectedColStats.ndv.get.toDouble) - 1.0d)
            assert(error <= rsd * 3.0d, "Error should be within 3 std. errors.")
    ```
    What do you think?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81103501
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,355 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    +    def assertAnalyzeColumnCommand(analyzeCommand: String, c: Class[_]) {
    +      val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +      val operators = parsed.collect {
    +        case a: AnalyzeColumnCommand => a
    +        case o => o
    +      }
    +      assert(operators.size == 1)
    +      if (operators.head.getClass != c) {
    +        fail(
    +          s"""$analyzeCommand expected command: $c, but got ${operators.head}
    +             |parsed command:
    +             |$parsed
    +           """.stripMargin)
    +      }
    +    }
    +
    +    val table = "table"
    +    assertAnalyzeColumnCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    intercept[ParseException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +  }
    +
    +  test("analyzing columns of non-atomic types is not supported") {
    +    val tableName = "tbl"
    +    withTable(tableName) {
    +      Seq(ArrayData(Seq(1, 2, 3), Seq(Seq(1, 2, 3)))).toDF().write.saveAsTable(tableName)
    +      val err = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS data")
    +      }
    +      assert(err.message.contains("Analyzing columns is not supported"))
    +    }
    +  }
    +
    +  test("check correctness of columns") {
    +    val table = "tbl"
    +    val colName1 = "abc"
    +    val colName2 = "x.yz"
    +    val quotedColName2 = s"`$colName2`"
    --- End diff --
    
    you can inline this variable, i.e.`CREATE TABLE $table ($colName1 int, `$colName2` string)`



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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65475 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65475/consoleFull)** for PR 15090 at commit [`761a9e0`](https://github.com/apache/spark/commit/761a9e0641ac6e6f4798d4be988ded0875b974a0).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `case class AnalyzeTableCommand(`


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65477 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65477/consoleFull)** for PR 15090 at commit [`9cdc722`](https://github.com/apache/spark/commit/9cdc722780445c62ed2c306ede0ebc4829dbdbe8).


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65941 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65941/consoleFull)** for PR 15090 at commit [`08df669`](https://github.com/apache/spark/commit/08df66937d8834c8e0b7300beea1973705f852b7).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79520564
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,228 @@
    +/*
    + * 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.hive
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.{AnalysisException, Row}
    +import org.apache.spark.sql.catalyst.plans.logical.BasicColStats
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +
    +  test("parse analyze column commands") {
    +    val table = "table"
    +    assertAnalyzeCommand(
    +      s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value",
    +      classOf[AnalyzeColumnCommand])
    +
    +    val noColumnError = intercept[AnalysisException] {
    +      sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS")
    +    }
    +    assert(noColumnError.message == "Need to specify the columns to analyze. Usage: " +
    +      "ANALYZE TABLE tbl COMPUTE STATISTICS FOR COLUMNS key, value")
    +
    +    withTable(table) {
    +      sql(s"CREATE TABLE $table (key INT, value STRING)")
    +      val invalidColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS k")
    +      }
    +      assert(invalidColError.message == s"Invalid column name: k")
    +
    +      val duplicateColError = intercept[AnalysisException] {
    +        sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, key")
    +      }
    +      assert(duplicateColError.message == s"Duplicate column name: key")
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "true") {
    +        val invalidErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS keY")
    +        }
    +        assert(invalidErr.message == s"Invalid column name: keY")
    +      }
    +
    +      withSQLConf("spark.sql.caseSensitive" -> "false") {
    +        val duplicateErr = intercept[AnalysisException] {
    +          sql(s"ANALYZE TABLE $table COMPUTE STATISTICS FOR COLUMNS key, value, vaLue")
    +        }
    +        assert(duplicateErr.message == s"Duplicate column name: vaLue")
    +      }
    +    }
    +  }
    +
    +  test("basic statistics for integral type columns") {
    +    val rdd = sparkContext.parallelize(Seq("1", null, "2", "3", null)).map { i =>
    +      if (i != null) Row(i.toByte, i.toShort, i.toInt, i.toLong) else Row(i, i, i, i)
    --- End diff --
    
    @HyukjinKwon Seems better. Let me change the code based on this. Thanks.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by hvanhovell <gi...@git.apache.org>.
Github user hvanhovell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78717769
  
    --- 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,
    --- End diff --
    
    Please use a `TableIdentifier` here.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65754 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65754/consoleFull)** for PR 15090 at commit [`5f6b581`](https://github.com/apache/spark/commit/5f6b5817d59c1b6bb48563357f625521e7c56236).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    This pr has been updated. Can you take another look? @rxin @hvanhovell @cloud-fan @gatorsmile 


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r78689452
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsSuite.scala ---
    @@ -330,14 +332,237 @@ class StatisticsSuite extends QueryTest with TestHiveSingleton with SQLTestUtils
           val dfNoCols = spark.createDataFrame(rddNoCols, StructType(Seq.empty))
           dfNoCols.write.format("json").saveAsTable(table_no_cols)
           sql(s"ANALYZE TABLE $table_no_cols COMPUTE STATISTICS")
    -      checkStats(
    +      checkTableStats(
             table_no_cols,
             isDataSourceTable = true,
             hasSizeInBytes = true,
             expectedRowCounts = Some(10))
         }
       }
     
    +  private def checkColStats(
    --- End diff --
    
    I used `checkTableStats` in some cases for column stats, so maybe put all test cases for table/column stats into a separate file?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80632476
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,180 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStat, LogicalPlan, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val db = tableIdent.database.getOrElse(sessionState.catalog.getCurrentDatabase)
    +    val tableIdentWithDB = TableIdentifier(tableIdent.table, Some(db))
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdentWithDB))
    +
    +    relation match {
    +      case catalogRel: CatalogRelation =>
    +        updateStats(catalogRel.catalogTable,
    +          AnalyzeTableCommand.calculateTotalSize(sessionState, catalogRel.catalogTable))
    +
    +      case logicalRel: LogicalRelation if logicalRel.catalogTable.isDefined =>
    +        updateStats(logicalRel.catalogTable.get, logicalRel.relation.sizeInBytes)
    +
    +      case otherRelation =>
    +        throw new AnalysisException("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      val (rowCount, columnStats) = computeColStats(sparkSession, relation)
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdentWithDB)
    --- End diff --
    
    We need to refresh the `stats` property of `catalogTable` in cached data source tables


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    > Do you still remember the test case I showed you in table-level statistics? A table with zero column. Can you add a test case for that scenario?
    
    What's the purpose of adding this test?


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79546838
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/command/AnalyzeColumnCommand.scala ---
    @@ -0,0 +1,168 @@
    +/*
    + * 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, TableIdentifier}
    +import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
    +import org.apache.spark.sql.catalyst.catalog.{CatalogRelation, CatalogTable}
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.expressions.aggregate._
    +import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +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(
    +    tableIdent: TableIdentifier,
    +    columnNames: Seq[String]) extends RunnableCommand {
    +
    +  override def run(sparkSession: SparkSession): Seq[Row] = {
    +    val sessionState = sparkSession.sessionState
    +    val relation = EliminateSubqueryAliases(sessionState.catalog.lookupRelation(tableIdent))
    +
    +    // check correctness of column names
    +    val attributesToAnalyze = mutable.MutableList[Attribute]()
    +    val caseSensitive = sessionState.conf.caseSensitiveAnalysis
    +    columnNames.foreach { col =>
    +      val exprOption = relation.output.find { attr =>
    +        if (caseSensitive) attr.name == col else attr.name.equalsIgnoreCase(col)
    +      }
    +      val expr = exprOption.getOrElse(throw new AnalysisException(s"Invalid column name: $col."))
    +      // do deduplication
    +      if (!attributesToAnalyze.contains(expr)) {
    +        attributesToAnalyze += expr
    +      }
    +    }
    +
    +    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("ANALYZE TABLE is not supported for " +
    +          s"${otherRelation.nodeName}.")
    +    }
    +
    +    def updateStats(catalogTable: CatalogTable, newTotalSize: Long): Unit = {
    +      // Collect statistics per column.
    +      // The first element in the result will be the overall row count, the following elements
    +      // will be structs containing all column stats.
    +      // The layout of each struct follows the layout of the ColumnStats.
    +      val ndvMaxErr = sessionState.conf.ndvMaxError
    +      val expressions = Count(Literal(1)).toAggregateExpression() +:
    +        attributesToAnalyze.map(ColumnStatsStruct(_, ndvMaxErr))
    +      val namedExpressions = expressions.map(e => Alias(e, e.toString)())
    +      val statsRow = Dataset.ofRows(sparkSession, Aggregate(Nil, namedExpressions, relation))
    +        .queryExecution.toRdd.collect().head
    +
    +      // unwrap the result
    +      val rowCount = statsRow.getLong(0)
    +      val columnStats = attributesToAnalyze.zipWithIndex.map { case (expr, i) =>
    +        (expr.name, ColumnStatsStruct.unwrapStruct(statsRow, i + 1, expr))
    +      }.toMap
    +
    +      val statistics = Statistics(
    +        sizeInBytes = newTotalSize,
    +        rowCount = Some(rowCount),
    +        colStats = columnStats ++ catalogTable.stats.map(_.colStats).getOrElse(Map()))
    +      sessionState.catalog.alterTable(catalogTable.copy(stats = Some(statistics)))
    +      // Refresh the cached data source table in the catalog.
    +      sessionState.catalog.refreshTable(tableIdent)
    --- End diff --
    
    BTW, you also have the same issue in `AnalyzeTableCommand`


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by srinathshankar <gi...@git.apache.org>.
Github user srinathshankar commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79891286
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
           s"isBroadcastable=$isBroadcastable"
    -    ).filter(_.nonEmpty).mkString("", ", ", "")
    +    ).filter(_.nonEmpty).mkString(", ")
    +  }
    +}
    +
    +/**
    + * Statistics for a column.
    + * @param ndv Number of distinct values of the column.
    + */
    +case class ColumnStats(
    +    dataType: DataType,
    +    numNulls: Long,
    +    max: Option[Any] = None,
    +    min: Option[Any] = None,
    +    ndv: Option[Long] = None,
    +    avgColLen: Option[Double] = None,
    +    maxColLen: Option[Long] = None,
    +    numTrues: Option[Long] = None,
    --- End diff --
    
    This seems special-cased for booleans. If we're planning to maintain histograms or frequent values, it would seem that this is unnecessary


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65950 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65950/consoleFull)** for PR 15090 at commit [`7cd8f14`](https://github.com/apache/spark/commit/7cd8f144c3d64fc407f42b069bd7a53d70604974).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r80156525
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Statistics.scala ---
    @@ -32,19 +34,74 @@ package org.apache.spark.sql.catalyst.plans.logical
      * @param sizeInBytes Physical size in bytes. For leaf operators this defaults to 1, otherwise it
      *                    defaults to the product of children's `sizeInBytes`.
      * @param rowCount Estimated number of rows.
    + * @param colStats Column-level statistics.
      * @param isBroadcastable If true, output is small enough to be used in a broadcast join.
      */
     case class Statistics(
         sizeInBytes: BigInt,
         rowCount: Option[BigInt] = None,
    +    colStats: Map[String, ColumnStats] = Map.empty,
         isBroadcastable: Boolean = false) {
    +
       override def toString: String = "Statistics(" + simpleString + ")"
     
       /** Readable string representation for the Statistics. */
       def simpleString: String = {
         Seq(s"sizeInBytes=$sizeInBytes",
           if (rowCount.isDefined) s"rowCount=${rowCount.get}" else "",
    +      if (colStats.nonEmpty) s"colStats=$colStats" else "",
    --- End diff --
    
    I am not sure whether we should do this. Hive does not show it in the `DESC FORMATTED/EXTENDED`, right? The string could be super long when the table has many columns.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test PASSed.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Merged build finished. Test FAILed.


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79965370
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/internal/SessionState.scala ---
    @@ -186,13 +187,27 @@ private[sql] class SessionState(sparkSession: SparkSession) {
       }
     
       /**
    -   * Analyzes the given table in the current database to generate statistics, which will be
    +   * Analyzes the given table in the current database to generate table-level statistics, which
    +   * will be used in query optimizations.
    +   */
    +  def analyzeTable(tableIdent: TableIdentifier, noscan: Boolean = true): Unit = {
    +    AnalyzeTableCommand(tableIdent, noscan).run(sparkSession)
    +  }
    +
    +  /**
    +   * Analyzes the given columns in the table to generate column-level statistics, which will be
        * used in query optimizations.
    -   *
    -   * Right now, it only supports catalog tables and it only updates the size of a catalog table
    -   * in the external catalog.
        */
    -  def analyze(tableName: String, noscan: Boolean = true): Unit = {
    -    AnalyzeTableCommand(tableName, noscan).run(sparkSession)
    +  def analyzeTableColumns(tableIdent: TableIdentifier, columnNames: Seq[String]): Unit = {
    +    AnalyzeColumnCommand(tableIdent, columnNames).run(sparkSession)
    +  }
    +
    +  // This api is used for testing.
    +  def computeColumnStats(tableName: String, columnNames: Seq[String]): Map[String, ColumnStats] = {
    --- End diff --
    
    Avoid adding any testing-only API, if possible.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    LGTM except the above minor comments. 
    
    Test cases mentioned above need to be added to `sql/hive/`, since the correctness could be affected by the behaviors of Hive metastore .


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81103116
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/StatisticsColumnSuite.scala ---
    @@ -0,0 +1,355 @@
    +/*
    + * 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
    +
    +import java.sql.{Date, Timestamp}
    +
    +import org.apache.spark.sql.catalyst.{InternalRow, TableIdentifier}
    +import org.apache.spark.sql.catalyst.parser.ParseException
    +import org.apache.spark.sql.catalyst.plans.logical.ColumnStat
    +import org.apache.spark.sql.catalyst.util.DateTimeUtils
    +import org.apache.spark.sql.execution.command.AnalyzeColumnCommand
    +import org.apache.spark.sql.test.SQLTestData.ArrayData
    +import org.apache.spark.sql.types._
    +
    +class StatisticsColumnSuite extends StatisticsTest {
    +  import testImplicits._
    +
    +  test("parse analyze column commands") {
    --- End diff --
    
    please follow the style in `DDLCommandSuite` to write test for parser rules


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by cloud-fan <gi...@git.apache.org>.
Github user cloud-fan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r81450136
  
    --- Diff: sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveExternalCatalog.scala ---
    @@ -473,15 +476,21 @@ private[spark] class HiveExternalCatalog(conf: SparkConf, hadoopConf: Configurat
           }
         }
         // construct Spark's statistics from information in Hive metastore
    -    if (catalogTable.properties.contains(STATISTICS_TOTAL_SIZE)) {
    -      val totalSize = BigInt(catalogTable.properties.get(STATISTICS_TOTAL_SIZE).get)
    -      // TODO: we will compute "estimatedSize" when we have column stats:
    -      // average size of row * number of rows
    +    if (catalogTable.properties.filterKeys(_.startsWith(STATISTICS_PREFIX)).nonEmpty) {
    --- End diff --
    
    should we make `catalogTable.properties.filterKeys(_.startsWith(STATISTICS_PREFIX))` a variable? it's used twice


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


[GitHub] spark pull request #15090: [SPARK-17073] [SQL] generate column-level statist...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15090#discussion_r79550718
  
    --- Diff: sql/hive/src/test/scala/org/apache/spark/sql/hive/StatisticsTest.scala ---
    @@ -0,0 +1,139 @@
    +/*
    + * 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.hive
    +
    +import org.apache.spark.sql.{DataFrame, QueryTest}
    +import org.apache.spark.sql.catalyst.plans.logical.{ColumnStats, Statistics}
    +import org.apache.spark.sql.execution.command.{AnalyzeColumnCommand, AnalyzeTableCommand}
    +import org.apache.spark.sql.execution.datasources.LogicalRelation
    +import org.apache.spark.sql.hive.test.TestHiveSingleton
    +import org.apache.spark.sql.test.SQLTestUtils
    +import org.apache.spark.sql.types._
    +
    +trait StatisticsTest extends QueryTest with TestHiveSingleton with SQLTestUtils {
    +
    +  def assertAnalyzeCommand(analyzeCommand: String, c: Class[_]) {
    +    val parsed = spark.sessionState.sqlParser.parsePlan(analyzeCommand)
    +    val operators = parsed.collect {
    +      case a: AnalyzeTableCommand => a
    +      case b: AnalyzeColumnCommand => b
    +      case o => o
    +    }
    +
    +    assert(operators.size === 1)
    +    if (operators(0).getClass() != c) {
    +      fail(
    +        s"""$analyzeCommand expected command: $c, but got ${operators(0)}
    +           |parsed command:
    +           |$parsed
    +           """.stripMargin)
    --- End diff --
    
    Please update the syntax.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by wzhfy <gi...@git.apache.org>.
Github user wzhfy commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    retest this please


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    **[Test build #65745 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/65745/consoleFull)** for PR 15090 at commit [`ec02b2a`](https://github.com/apache/spark/commit/ec02b2a8b7bfb9c10d4d47e2678a44ec0f2f8af8).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


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


[GitHub] spark issue #15090: [SPARK-17073] [SQL] generate column-level statistics

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/15090
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/65935/
    Test FAILed.


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