简体   繁体   中英

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. I have to convert this into a new dataframe/dataset which has only 2 columns and without any comma delimiters. The value in column_1 and its corresponding name in Column_2 should be written to output. Similarly for column_3 and column_4. If both are column_1 and column_2 are null, they are not required in output.

Expected 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?

Scala solution - I think should work in Java. Basically just handle col1, col2 separately from col3, col4, and union the results. Lots of wrangling with 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|
+------------+------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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