如何在spark map函数中输出多个(键,值)

how to output multiple (key,value) in spark map function

输入数据格式如下:

+--------------------+-------------+--------------------+
|           StudentID|       Right |             Wrong  |
+--------------------+-------------+--------------------+
|       studentNo01  |       a,b,c |            x,y,z   |
+--------------------+-------------+--------------------+
|       studentNo02  |         c,d |              v,w   |
+--------------------+-------------+--------------------+

输出格式如下():

+--------------------+---------+
|           key      |    value|
+--------------------+---------+
|     studentNo01,a  |       1 |
+--------------------+---------+
|     studentNo01,b  |       1 |
+--------------------+---------+
|     studentNo01,c  |       1 | 
+--------------------+---------+
|     studentNo01,x  |       0 | 
+--------------------+---------+
|     studentNo01,y  |       0 | 
+--------------------+---------+
|     studentNo01,z  |       0 | 
+--------------------+---------+
|     studentNo02,c  |       1 | 
+--------------------+---------+
|     studentNo02,d  |       1 | 
+--------------------+---------+
|     studentNo02,v  |       0 | 
+--------------------+---------+
|     studentNo02,w  |       0 | 
+--------------------+---------+

正确的是 1,错误的是 0。

我想用Spark map函数或者udf来处理这些数据,但是不知道怎么处理。你能帮我吗?谢谢。

使用拆分和爆炸两次并进行并集

val df = List(
  ("studentNo01","a,b,c","x,y,z"),
  ("studentNo02","c,d","v,w")
  ).toDF("StudenID","Right","Wrong")

+-----------+-----+-----+
|   StudenID|Right|Wrong|
+-----------+-----+-----+
|studentNo01|a,b,c|x,y,z|
|studentNo02|  c,d|  v,w|
+-----------+-----+-----+


val pair = (
  df.select('StudenID,explode(split('Right,",")))
    .select(concat_ws(",",'StudenID,'col).as("key"))
    .withColumn("value",lit(1))
).unionAll(
  df.select('StudenID,explode(split('Wrong,",")))
    .select(concat_ws(",",'StudenID,'col).as("key"))
    .withColumn("value",lit(0))
)


+-------------+-----+
|          key|value|
+-------------+-----+
|studentNo01,a|    1|
|studentNo01,b|    1|
|studentNo01,c|    1|
|studentNo02,c|    1|
|studentNo02,d|    1|
|studentNo01,x|    0|
|studentNo01,y|    0|
|studentNo01,z|    0|
|studentNo02,v|    0|
|studentNo02,w|    0|
+-------------+-----+

可以如下转换为RDD

val rdd = pair.map(r => (r.getString(0),r.getInt(1)))