将常量struct列添加到Spark DataFrame

时间:2017-06-12 13:01:56

标签: apache-spark dataframe apache-spark-sql spark-dataframe

我想从数据库集合中加载struct,并将其作为常量列附加到目标DataFrame中的每一行。

我可以将我需要的列作为DataFrame加载一行,然后执行crossJoin将其粘贴到目标的每一行:

val parentCollectionDF = /* ... load a single row from the database */
val constantCol = broadcast(parentCollectionDF.select("my_column"))
val result = childCollectionDF.crossJoin(constantCol)

它有效但感觉很浪费:子集合的每一行的数据都是常量,但是crossJoin将它复制到每一行。

如果我可以对值进行硬编码,我可以使用像childCollection.withColumn("my_column", struct(lit(val1) as "field1", lit(val2) as "field2" /* etc. */))这样的东西,但我不能提前知道它们;我需要从父集合加载结构。

我正在寻找的是:

childCollection.withColumn("my_column",
  lit(parentCollectionDF.select("my_column").take(1).getStruct(0))

...但我可以从the code for literals看到只有基本类型可以用作lit()的参数。没法在这里传递GenericRowWithSchema或案例类。

这样做有什么不那么笨拙的方法吗? (Spark 2.1.1,Scala)

[edit:与this question不同,它解释了如何使用文字(硬编码)常量添加结构。我的结构需要动态加载。]

0 个答案:

没有答案
相关问题