[英]Handling comma delimited columns with dependency on another column in Spark dataset
I have the below spark dataframe/dataset.我有以下火花数据框/数据集。
column_1 column_2 column_3 column_4
A,B NameA,NameB F NameF
C NameC NULL NULL
NULL NULL D,E NameD,NULL
G NULL H NameH
I NameI J NULL
All the above 4 columns are comma delimited.以上 4 列均以逗号分隔。 I have to convert this into a new dataframe/dataset which has only 2 columns and without any comma delimiters.
我必须将其转换为只有 2 列且没有任何逗号分隔符的新数据框/数据集。 The value in column_1 and its corresponding name in Column_2 should be written to output.
column_1 中的值及其在 Column_2 中的对应名称应写入 output。 Similarly for column_3 and column_4.
对于 column_3 和 column_4 也是如此。 If both are column_1 and column_2 are null, they are not required in output.
如果 column_1 和 column_2 都是 null,则在 output 中不需要它们。
Expected output:预期 output:
out_column_1 out_column_2
A NameA
B NameB
F NameF
C NameC
D NameD
E NULL
G NULL
H NameH
I NameI
J NULL
Is there a way to achieve this in Java spark without using UDF's?有没有办法在不使用 UDF 的情况下在 Java spark 中实现这一点?
Scala solution - I think should work in Java. Scala 解决方案 - 我认为应该在 Java 中工作。 Basically just handle col1, col2 separately from col3, col4, and union the results.
基本上只需将 col1、col2 与 col3、col4 分开处理,然后合并结果。 Lots of wrangling with arrays.
与 arrays 有很多争论。
// maybe replace this with Dataset<Row> result = ... in Java
val result = df.select(
split(col("column_1"), ",").alias("column_1"),
split(col("column_2"), ",").alias("column_2")
).filter(
"column_1 is not null"
).select(
explode(
arrays_zip(
col("column_1"),
coalesce(col("column_2"), array(lit(null)))
)
)
).select(
"col.*"
).union(
df.select(
split(col("column_3"), ",").alias("column_3"),
split(col("column_4"), ",").alias("column_4")
).filter(
"column_3 is not null"
).select(
explode(
arrays_zip(
col("column_3"),
coalesce(col("column_4"), array(lit(null)))
)
)
).select("col.*")
).toDF(
"out_column_1", "out_column_2"
)
result.show
+------------+------------+
|out_column_1|out_column_2|
+------------+------------+
| A| NameA|
| B| NameB|
| C| NameC|
| G| null|
| I| NameI|
| F| NameF|
| D| NameD|
| E| null|
| H| NameH|
| J| null|
+------------+------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.