另一种选择是我自己的虚构数据,您可以根据这些数据进行定制,而无需自定义项:
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.expressions._
import org.apache.spark.sql.functions._
val df = Seq(
(1, "111@#cat@@666", "222@@fritz@@777"),
(2, "AAA@@cat@@555", "BBB@@felix@@888"),
(3, "HHH@@mouse@@yyy", "123##mickey#@ZZZ")
).toDF("c0", "c1", "c2")
val df2 = df.withColumn( "c_split", split(col("c1"), ("(@#)|(@@)|(##)|(#@)") ))
.union(df.withColumn("c_split", split(col("c2"), ("(@#)|(@@)|(##)|(#@)") )) )
df2.show(false)
df2.printSchema()
val df3 = df2.groupBy(col("c0")).agg(collect_list(col("c_split")).as("List_of_Data") )
df3.show(false)
df3.printSchema()
给出答案,但没有ListBuffer-真的有必要吗?如下所示:
+---+---------------+----------------+------------------+
|c0 |c1 |c2 |c_split |
+---+---------------+----------------+------------------+
|1 |111@#cat@@666 |222@@fritz@@777 |[111, cat, 666] |
|2 |AAA@@cat@@555 |BBB@@felix@@888 |[AAA, cat, 555] |
|3 |HHH@@mouse@@yyy|123##mickey#@ZZZ|[HHH, mouse, yyy] |
|1 |111@#cat@@666 |222@@fritz@@777 |[222, fritz, 777] |
|2 |AAA@@cat@@555 |BBB@@felix@@888 |[BBB, felix, 888] |
|3 |HHH@@mouse@@yyy|123##mickey#@ZZZ|[123, mickey, ZZZ]|
+---+---------------+----------------+------------------+
root
|-- c0: integer (nullable = false)
|-- c1: string (nullable = true)
|-- c2: string (nullable = true)
|-- c_split: array (nullable = true)
| |-- element: string (containsNull = true)
+---+---------------------------------------+
|c0 |List_of_Data |
+---+---------------------------------------+
|1 |[[111, cat, 666], [222, fritz, 777]] |
|3 |[[HHH, mouse, yyy], [123, mickey, ZZZ]]|
|2 |[[AAA, cat, 555], [BBB, felix, 888]] |
+---+---------------------------------------+
root
|-- c0: integer (nullable = false)
|-- List_of_Data: array (nullable = true)
| |-- element: array (containsNull = true)
| | |-- element: string (containsNull = true)