繁体   English   中英

合并 Scala Spark sql 模式

[英]Merging Scala Spark sql schemas

我正在尝试合并两个数据帧并创建一个数据帧,其中包含一个包含另一个数据帧作为数组的新列。 有谁知道这如何在 Scala 中实现?

//架构1

PRIM_KEY: decimal(20,0) (nullable = true)
|-- SOME_DECIMAL: decimal(20,0) (nullable = true)
|-- SOME_INTEGER: integer (nullable = true)

//模式2

PRIM_KEY: decimal(20,0) (nullable = true)
|-- COLUMN1: string (nullable = false)
|-- COLUMN2: string (nullable = false)

//结果模式

RIM_KEY: decimal(20,0) (nullable = true)
|-- SOME_DECIMAL: decimal(20,0) (nullable = true)
|-- SOME_INTEGER: integer (nullable = true)
|-- an_array: array (nullable = true)
|    |-- element: String (containsNull = false)

一种方法是创建一个UDF ,结合两个列表成为一个,执行一个groupBy上加入dataframes,并应用UDF如以下:

val df1 = Seq(
  (1, 100.1, 10),
  (2, 200.2, 20)
).toDF("pk", "col1", "col2")

val df2 = Seq(
  (1, "a1", "b1"),
  (1, "c1", "d1"),
  (2, "a2", "b2")
).toDF("pk", "str_col1", "str_col2")

def combineLists = udf(
  (a: Seq[String], b: Seq[String]) => a ++ b
)

val df3 = df1.join(df2, Seq("pk")).
  groupBy(df1("pk"), df1("col1"), df1("col2")).agg(
    combineLists(collect_list(df2("str_col1")), collect_list(df2("str_col2"))).alias("arr_col")
  ).
  select(df1("pk"), df1("col1"), df1("col2"), col("arr_col"))

df3.show
+---+-----+----+----------------+
| pk| col1|col2|         arr_col|
+---+-----+----+----------------+
|  1|100.1|  10|[c1, a1, d1, b1]|
|  2|200.2|  20|        [a2, b2]|
+---+-----+----+----------------+

您正在寻求的结果:

RIM_KEY: decimal(20,0) (nullable = true)
|-- SOME_DECIMAL: decimal(20,0) (nullable = true)
|-- SOME_INTEGER: integer (nullable = true)
|-- an_array: array (nullable = true)
|    |-- element: String (containsNull = false)

我先告诉你:

数组 (nullable = true) 不是数据类型,而是数据结构。 因此,您根本无法将架构定义为 DataType 数组。

一种方法是使用 concat_ws 连接字符串并对第二个数据集执行 withcolumn 操作。

EG:

val tmpDf = test2Df.select(concat_ws(",", col("NAME"), col("CLASS")).as("ARRAY_COLUMN"))
val mergedDf = test1Df.withColumn("ARRAY_COLUMN",tmpDf.col("ARRAY_COLUMN"))

我不明白使用数组类型作为架构的用例是什么,但您可以使用连接结果并转换为数组。

希望这对你有帮助,我知道在这里回答有点晚了,但如果它现在对你有帮助,我仍然会很高兴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM