好吧,事情再简单不过了。让我们考虑一下您正在处理的相同数据,并从那里逐步进行
// A case class for our sample table
case class Testing(name: String, age: Int, salary: Int)
// Create an RDD with some data
val x = sc.parallelize(Array(
Testing(null, 21, 905),
Testing("Noelia", 26, 1130),
Testing("Pilar", 52, 1890),
Testing("Roberto", 31, 1450)
))
// Convert RDD to a DataFrame
val df = sqlContext.createDataFrame(x)
// For SQL usage we need to register the table
df.registerTempTable("df")
sqlContext.sql("select collect_list(age) as age from df").show
// +----------------+
// | age|
// +----------------+
// |[21, 26, 52, 31]|
// +----------------+
sqlContext.sql("select collect_list(collect_list(age), collect_list(salary)) as arrayInt from df").show
正如错误消息所示:
org.apache.spark.sql.AnalysisException: No handler for Hive udf class
org.apache.hadoop.hive.ql.udf.generic.GenericUDAFCollectList because: Exactly one argument is expected..; line 1 pos 52 [...]
collest_list
仅需要一个参数。让我们检查一下文档here http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions%24.
它实际上需要一个参数!但让我们进一步了解函数对象的文档。您似乎已经注意到,数组函数允许您从 Column 或重复的 Column 参数创建新的数组列。那么让我们使用它:
sqlContext.sql("select array(collect_list(age), collect_list(salary)) as arrayInt from df").show(false)
数组函数确实从由collect_list预先创建的列列表中创建了一个列,包括年龄和薪水:
// +-------------------------------------------------------------------+
// |arrayInt |
// +-------------------------------------------------------------------+
// |[WrappedArray(21, 26, 52, 31), WrappedArray(905, 1130, 1890, 1450)]|
// +-------------------------------------------------------------------+
我们接下来该去哪里?
您必须记住,DataFrame 中的 Row 只是由 Row 包装的另一个集合。
我要做的第一件事就是处理该系列。那么我们如何展平WrappedArray[WrappedArray[Int]]
?
Scala 有点神奇,你只需要使用.flatten
import scala.collection.mutable.WrappedArray
val firstRow: mutable.WrappedArray[mutable.WrappedArray[Int]] =
sqlContext.sql("select array(collect_list(age), collect_list(salary)) as arrayInt from df")
.first.get(0).asInstanceOf[WrappedArray[WrappedArray[Int]]]
// res26: scala.collection.mutable.WrappedArray[scala.collection.mutable.WrappedArray[Int]] =
// WrappedArray(WrappedArray(21, 26, 52, 31), WrappedArray(905, 1130, 1890, 1450))
firstRow.flatten
// res27: scala.collection.mutable.IndexedSeq[Int] = ArrayBuffer(21, 26, 52, 31, 905, 1130, 1890, 1450)
现在让我们将其包装在 UDF 中,以便我们可以在 DataFrame 上使用它:
def flatten(array: WrappedArray[WrappedArray[Int]]) = array.flatten
sqlContext.udf.register("flatten", flatten(_: WrappedArray[WrappedArray[Int]]))
由于我们注册了 UDF,我们现在可以在 sqlContext 中使用它:
sqlContext.sql("select flatten(array(collect_list(age), collect_list(salary))) as arrayInt from df").show(false)
// +---------------------------------------+
// |arrayInt |
// +---------------------------------------+
// |[21, 26, 52, 31, 905, 1130, 1890, 1450]|
// +---------------------------------------+
我希望这有帮助 !