cloud-fan commented on code in PR #47884: URL: https://github.com/apache/spark/pull/47884#discussion_r1741015178
########## sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTranspose.scala: ########## @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.catalyst.analysis + +import org.apache.spark.sql.AnalysisException +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Alias, Ascending, Attribute, AttributeReference, Cast, IsNotNull, Literal, SortOrder} +import org.apache.spark.sql.catalyst.plans.logical.{Filter, Limit, LogicalPlan, Project, Sort, Transpose} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.types.{AtomicType, DataType, StringType} +import org.apache.spark.unsafe.types.UTF8String + + +/** + * Rule that resolves and transforms an `UnresolvedTranspose` logical plan into a `Transpose` + * logical plan, which effectively transposes a DataFrame by turning rows into columns based + * on a specified index column. + * + * The high-level logic for the transpose operation is as follows: + * - If the index column is not provided, the first column of the DataFrame is used as the + * default index column. + * - The index column is cast to `StringType` to ensure consistent column naming. + * - Non-index columns are cast to a common data type, determined by finding the least + * common type that can accommodate all non-index columns. + * - The data is sorted by the index column, and rows with `null` index values are excluded + * from the transpose operation. + * - The transposed DataFrame is constructed by turning the original rows into columns, with + * the index column values becoming the new column names and the non-index column values + * populating the transposed data. + */ +class ResolveTranspose(sparkSession: SparkSession) extends Rule[LogicalPlan] { + + private def leastCommonType(dataTypes: Seq[DataType]): DataType = { + if (dataTypes.isEmpty) { + StringType + } else { + dataTypes.reduce { (dt1, dt2) => + TypeCoercion.findTightestCommonType(dt1, dt2).getOrElse { + throw new AnalysisException( + errorClass = "TRANSPOSE_NO_LEAST_COMMON_TYPE", + messageParameters = Map( + "dt1" -> dt1.toString, + "dt2" -> dt2.toString) + ) + } + } + } + } + + private def transposeMatrix( + fullCollectedRows: Array[InternalRow], + nonIndexColumnNames: Seq[String], + nonIndexColumnDataTypes: Seq[DataType]): Array[Array[Any]] = { + val numTransposedRows = fullCollectedRows.head.numFields - 1 + val numTransposedCols = fullCollectedRows.length + 1 + val finalMatrix = Array.ofDim[Any](numTransposedRows, numTransposedCols) + + // Example of the original DataFrame: + // +---+-----+-----+ + // | id|col1 |col2 | + // +---+-----+-----+ + // | 1| 10 | 20 | + // | 2| 30 | 40 | + // +---+-----+-----+ + // + // After transposition, the finalMatrix will look like: + // [ + // ["col1", 10, 30], // Transposed row for col1 + // ["col2", 20, 40] // Transposed row for col2 + // ] + + for (i <- 0 until numTransposedRows) { + // Insert non-index column name as the first element in each transposed row + finalMatrix(i)(0) = UTF8String.fromString(nonIndexColumnNames(i)) + + for (j <- 1 until numTransposedCols) { + // Insert the transposed data + + // Example: If j = 2, then row = fullCollectedRows(1) + // This corresponds to the second row of the original DataFrame: InternalRow(2, 30, 40) + val row = fullCollectedRows(j - 1) + + // Example: If i = 0 (for "col1"), and j = 2, + // then finalMatrix(0)(2) corresponds to row.get(1, nonIndexColumnDataTypes(0)), + // which accesses the value 30 from InternalRow(2, 30, 40) + finalMatrix(i)(j) = row.get(i + 1, nonIndexColumnDataTypes(i)) + } + } + finalMatrix + } + + override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsWithPruning( + _.containsPattern(TreePattern.UNRESOLVED_TRANSPOSE)) { + case t @ UnresolvedTranspose(indexColumnOpt, child) if child.resolved => Review Comment: shall we also wait for the index column to be resolved first? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
