-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[SPARK-8992] [SQL] Add pivot to dataframe api #7841
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
599e9e0
32860d2
d8cbd04
e369f15
605c32e
f2827ea
403f966
d8e473c
2417548
1af796d
6e3b133
04d643c
88dd513
12a8270
676f1ac
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,8 +24,8 @@ import org.apache.spark.annotation.Experimental | |
| import org.apache.spark.sql.catalyst.analysis.{UnresolvedFunction, UnresolvedAlias, UnresolvedAttribute, Star} | ||
| import org.apache.spark.sql.catalyst.expressions._ | ||
| import org.apache.spark.sql.catalyst.expressions.aggregate._ | ||
| import org.apache.spark.sql.catalyst.plans.logical.{Rollup, Cube, Aggregate} | ||
| import org.apache.spark.sql.types.NumericType | ||
| import org.apache.spark.sql.catalyst.plans.logical.{Pivot, Rollup, Cube, Aggregate} | ||
| import org.apache.spark.sql.types.{StringType, NumericType} | ||
|
|
||
|
|
||
| /** | ||
|
|
@@ -50,14 +50,8 @@ class GroupedData protected[sql]( | |
| aggExprs | ||
| } | ||
|
|
||
| val aliasedAgg = aggregates.map { | ||
| // Wrap UnresolvedAttribute with UnresolvedAlias, as when we resolve UnresolvedAttribute, we | ||
| // will remove intermediate Alias for ExtractValue chain, and we need to alias it again to | ||
| // make it a NamedExpression. | ||
| case u: UnresolvedAttribute => UnresolvedAlias(u) | ||
| case expr: NamedExpression => expr | ||
| case expr: Expression => Alias(expr, expr.prettyString)() | ||
| } | ||
| val aliasedAgg = aggregates.map(alias) | ||
|
|
||
| groupType match { | ||
| case GroupedData.GroupByType => | ||
| DataFrame( | ||
|
|
@@ -68,9 +62,22 @@ class GroupedData protected[sql]( | |
| case GroupedData.CubeType => | ||
| DataFrame( | ||
| df.sqlContext, Cube(groupingExprs, df.logicalPlan, aliasedAgg)) | ||
| case GroupedData.PivotType(pivotCol, values) => | ||
| val aliasedGrps = groupingExprs.map(alias) | ||
| DataFrame( | ||
| df.sqlContext, Pivot(aliasedGrps, pivotCol, values, aggExprs, df.logicalPlan)) | ||
| } | ||
| } | ||
|
|
||
| // Wrap UnresolvedAttribute with UnresolvedAlias, as when we resolve UnresolvedAttribute, we | ||
| // will remove intermediate Alias for ExtractValue chain, and we need to alias it again to | ||
| // make it a NamedExpression. | ||
| private[this] def alias(expr: Expression): NamedExpression = expr match { | ||
| case u: UnresolvedAttribute => UnresolvedAlias(u) | ||
| case expr: NamedExpression => expr | ||
| case expr: Expression => Alias(expr, expr.prettyString)() | ||
| } | ||
|
|
||
| private[this] def aggregateNumericColumns(colNames: String*)(f: Expression => AggregateFunction) | ||
| : DataFrame = { | ||
|
|
||
|
|
@@ -273,6 +280,77 @@ class GroupedData protected[sql]( | |
| def sum(colNames: String*): DataFrame = { | ||
| aggregateNumericColumns(colNames : _*)(Sum) | ||
| } | ||
|
|
||
| /** | ||
| * (Scala-specific) Pivots a column of the current [[DataFrame]] and preform the specified | ||
| * aggregation. | ||
| * {{{ | ||
| * // Compute the sum of earnings for each year by course with each course as a separate column | ||
| * df.groupBy($"year").pivot($"course", "dotNET", "Java").agg(sum($"earnings")) | ||
| * // Or without specifying column values | ||
| * df.groupBy($"year").pivot($"course").agg(sum($"earnings")) | ||
| * }}} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How about we let users know that if no pivot values are provided, we will launch a job to find all distinct values of the pivot column?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Another question I have is that, what will happen if we have too many distinct values? I am wondering if we should always ask users to put pivot values?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a note below in the description of the values parameter
Right now if there is too many distinct values we probably get OOM. Obvious solve is to have some configurable maximum above which we give an error. Should I try to add that now?
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah. Let's add that check. In our error message, we can ask users to change the value of that conf (btw, let's make sure the default value of that conf is large enough for common use cases). |
||
| * @param pivotColumn Column to pivot | ||
| * @param values Optional list of values of pivotColumn that will be translated to columns in the | ||
| * output data frame. If values are not provided the method with do an immediate | ||
| * call to .distinct() on the pivot column. | ||
| * @since 1.6.0 | ||
| */ | ||
| @scala.annotation.varargs | ||
| def pivot(pivotColumn: Column, values: Column*): GroupedData = groupType match { | ||
| case _: GroupedData.PivotType => | ||
| throw new UnsupportedOperationException("repeated pivots are not supported") | ||
| case GroupedData.GroupByType => | ||
| val pivotValues = if (values.nonEmpty) { | ||
| values.map { | ||
| case Column(literal: Literal) => literal | ||
| case other => | ||
| throw new UnsupportedOperationException( | ||
| s"The values of a pivot must be literals, found $other") | ||
| } | ||
| } else { | ||
| // This is to prevent unintended OOM errors when the number of distinct values is large | ||
| val maxValues = df.sqlContext.conf.getConf(SQLConf.DATAFRAME_PIVOT_MAX_VALUES) | ||
| // Get the distinct values of the column and sort them so its consistent | ||
| val values = df.select(pivotColumn) | ||
| .distinct() | ||
| .sort(pivotColumn) | ||
| .map(_.get(0)) | ||
| .take(maxValues + 1) | ||
| .map(Literal(_)).toSeq | ||
| if (values.length > maxValues) { | ||
| throw new RuntimeException( | ||
| s"The pivot column $pivotColumn has more than $maxValues distinct values, " + | ||
| "this could indicate an error. " + | ||
| "If this was intended, set \"" + SQLConf.DATAFRAME_PIVOT_MAX_VALUES.key + "\" " + | ||
| s"to at least the number of distinct values of the pivot column.") | ||
| } | ||
| values | ||
| } | ||
| new GroupedData(df, groupingExprs, GroupedData.PivotType(pivotColumn.expr, pivotValues)) | ||
| case _ => | ||
| throw new UnsupportedOperationException("pivot is only supported after a groupBy") | ||
| } | ||
|
|
||
| /** | ||
| * Pivots a column of the current [[DataFrame]] and preform the specified aggregation. | ||
| * {{{ | ||
| * // Compute the sum of earnings for each year by course with each course as a separate column | ||
| * df.groupBy("year").pivot("course", "dotNET", "Java").sum("earnings") | ||
| * // Or without specifying column values | ||
| * df.groupBy("year").pivot("course").sum("earnings") | ||
| * }}} | ||
| * @param pivotColumn Column to pivot | ||
| * @param values Optional list of values of pivotColumn that will be translated to columns in the | ||
| * output data frame. If values are not provided the method with do an immediate | ||
| * call to .distinct() on the pivot column. | ||
| * @since 1.6.0 | ||
| */ | ||
| @scala.annotation.varargs | ||
| def pivot(pivotColumn: String, values: Any*): GroupedData = { | ||
| val resolvedPivotColumn = Column(df.resolve(pivotColumn)) | ||
| pivot(resolvedPivotColumn, values.map(functions.lit): _*) | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For the first version, maybe we can just have the API using |
||
| } | ||
|
|
||
|
|
||
|
|
@@ -307,4 +385,9 @@ private[sql] object GroupedData { | |
| * To indicate it's the ROLLUP | ||
| */ | ||
| private[sql] object RollupType extends GroupType | ||
|
|
||
| /** | ||
| * To indicate it's the PIVOT | ||
| */ | ||
| private[sql] case class PivotType(pivotCol: Expression, values: Seq[Literal]) extends GroupType | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.sql | ||
|
|
||
| import org.apache.spark.sql.functions._ | ||
| import org.apache.spark.sql.test.SharedSQLContext | ||
|
|
||
| class DataFramePivotSuite extends QueryTest with SharedSQLContext{ | ||
| import testImplicits._ | ||
|
|
||
| test("pivot courses with literals") { | ||
| checkAnswer( | ||
| courseSales.groupBy($"year").pivot($"course", lit("dotNET"), lit("Java")) | ||
| .agg(sum($"earnings")), | ||
| Row(2012, 15000.0, 20000.0) :: Row(2013, 48000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot year with literals") { | ||
| checkAnswer( | ||
| courseSales.groupBy($"course").pivot($"year", lit(2012), lit(2013)).agg(sum($"earnings")), | ||
| Row("dotNET", 15000.0, 48000.0) :: Row("Java", 20000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot courses with literals and multiple aggregations") { | ||
| checkAnswer( | ||
| courseSales.groupBy($"year").pivot($"course", lit("dotNET"), lit("Java")) | ||
| .agg(sum($"earnings"), avg($"earnings")), | ||
| Row(2012, 15000.0, 7500.0, 20000.0, 20000.0) :: | ||
| Row(2013, 48000.0, 48000.0, 30000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot year with string values (cast)") { | ||
| checkAnswer( | ||
| courseSales.groupBy("course").pivot("year", "2012", "2013").sum("earnings"), | ||
| Row("dotNET", 15000.0, 48000.0) :: Row("Java", 20000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot year with int values") { | ||
| checkAnswer( | ||
| courseSales.groupBy("course").pivot("year", 2012, 2013).sum("earnings"), | ||
| Row("dotNET", 15000.0, 48000.0) :: Row("Java", 20000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot courses with no values") { | ||
| // Note Java comes before dotNet in sorted order | ||
| checkAnswer( | ||
| courseSales.groupBy($"year").pivot($"course").agg(sum($"earnings")), | ||
| Row(2012, 20000.0, 15000.0) :: Row(2013, 30000.0, 48000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot year with no values") { | ||
| checkAnswer( | ||
| courseSales.groupBy($"course").pivot($"year").agg(sum($"earnings")), | ||
| Row("dotNET", 15000.0, 48000.0) :: Row("Java", 20000.0, 30000.0) :: Nil | ||
| ) | ||
| } | ||
|
|
||
| test("pivot max values inforced") { | ||
| sqlContext.conf.setConf(SQLConf.DATAFRAME_PIVOT_MAX_VALUES, 1) | ||
| intercept[RuntimeException]( | ||
| courseSales.groupBy($"year").pivot($"course") | ||
| ) | ||
| sqlContext.conf.setConf(SQLConf.DATAFRAME_PIVOT_MAX_VALUES, | ||
| SQLConf.DATAFRAME_PIVOT_MAX_VALUES.defaultValue.get) | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems we still need to check the number of children and make sure we have a single child?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It should now work fine with aggregate functions that have multiple children as long as they ignore updates when all values are null. For example
Corrshould work since it only updates its aggregation buffer if both its arguments are non null.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
oh, yes. You are right.