SparkSQL并在Java中的DataFrame上爆炸
有没有一种简单的方法如何在SparkSQL DataFrame
上使用数组列explode
? 它在Scala中相对简单,但是这个函数似乎在Java中不可用(如javadoc中所述)。
一个选项是使用SQLContext.sql(...)
并在查询中explode
function,但我正在寻找更好,更清洁的方式。 DataFrame
是从镶木地板文件加载的。
我以这种方式解决了这个问题:假设你有一个包含名为“positions”的职位描述的数组列,对于每个拥有“fullName”的人。
然后你从初始架构得到:
root |-- fullName: string (nullable = true) |-- positions: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- companyName: string (nullable = true) | | |-- title: string (nullable = true) ...
到架构:
root |-- personName: string (nullable = true) |-- companyName: string (nullable = true) |-- positionTitle: string (nullable = true)
通过做:
DataFrame personPositions = persons.select(persons.col("fullName").as("personName"), org.apache.spark.sql.functions.explode(persons.col("positions")).as("pos")); DataFrame test = personPositions.select(personPositions.col("personName"), personPositions.col("pos").getField("companyName").as("companyName"), personPositions.col("pos").getField("title").as("positionTitle"));
似乎可以使用org.apache.spark.sql.functions.explode(Column col)
和DataFrame.withColumn(String colName, Column col)
来将列替换为它的爆炸版本。