示例RDD如下:
(key1,(111,222,1)
(key1,(113,224,1)
(key1,(114,225,0)
(key1,(115,226,0)
(key1,(113,226,0)
(key1,(116,227,1)
(key1,(117,228,1)
(key2,(118,229,1)
我目前正在做一个火花项目。我想基于键过滤元组值中第三位置为'1'
和'0'
的第一个和最后一个元素。
是否可以用reduceByKey做到这一点?但是,经过研究,我没有找到实现所需目标的良好逻辑。我希望我的结果与下面显示的输出顺序相同。
预期输出:
(key1,(111,222,1)
(key1,(114,225,0)
(key1,(113,226,0)
(key1,(116,227,1)
(key2,(118,229,1)
非常感谢。
答案 0 :(得分:0)
如果我理解正确,则您希望每个键的第一个“ 1”,第一个“ 0”,最后一个“ 1”和最后一个“ 0”,并保持顺序。如果您是我,则可以使用SparkSQL API来完成。
首先,让我们构建您的RDD(顺便说一句,提供示例数据非常好,提供了足够的代码以便我们可以重现您所做的事情更好):
val seq = Seq(("key1",(111,222,1)),
("key1",(113,224,1)),
("key1",(114,225,0)),
("key1",(115,226,0)),
("key1",(113,226,0)),
("key1",(116,227,1)),
("key1",(117,228,1)),
("key2",(118,229,1)))
val rdd = sc.parallelize(seq)
// then I switch to dataframes, and add an id to be able to go back to
// the previous order
val df = rdd.toDF("key", "value").withColumn("id", monotonicallyIncreasingId)
df.show()
+----+-----------+------------+
| key| value| id|
+----+-----------+------------+
|key1|[111,222,1]| 8589934592|
|key1|[113,224,1]| 25769803776|
|key1|[114,225,0]| 42949672960|
|key1|[115,226,0]| 60129542144|
|key1|[113,226,0]| 77309411328|
|key1|[116,227,1]| 94489280512|
|key1|[117,228,1]|111669149696|
|key2|[118,229,1]|128849018880|
+----+-----------+------------+
现在,我们可以按“键”和“值._3”分组,保留min(id)及其最大值,然后炸回数据。但是,有了一个窗口,我们可以用一种更简单的方式做到这一点。让我们定义以下窗口:
val win = Window.partitionBy("key", "value._3").orderBy("id")
// now we compute the previous and next element of each id using resp. lag and lead
val big_df = df
.withColumn("lag", lag('id, 1) over win)
.withColumn("lead", lead('id, 1) over win)
big_df.show
+----+-----------+------------+-----------+------------+
| key| value| id| lag| lead|
+----+-----------+------------+-----------+------------+
|key1|[111,222,1]| 8589934592| null| 25769803776|
|key1|[113,224,1]| 25769803776| 8589934592| 94489280512|
|key1|[116,227,1]| 94489280512|25769803776|111669149696|
|key1|[117,228,1]|111669149696|94489280512| null|
|key1|[114,225,0]| 42949672960| null| 60129542144|
|key1|[115,226,0]| 60129542144|42949672960| 77309411328|
|key1|[113,226,0]| 77309411328|60129542144| null|
|key2|[118,229,1]|128849018880| null| null|
+----+-----------+------------+-----------+------------+
现在,我们看到您要跟踪的行是滞后等于空(第一个元素)或前导等于空(最后一个元素)的行。因此,让我们进行过滤,使用ID排序回到上一个顺序,然后选择所需的列:
val result = big_df
.where(('lag isNull) || ('lead isNull))
.orderBy('id)
.select("key", "value")
result.show
+----+-----------+
| key| value|
+----+-----------+
|key1|[111,222,1]|
|key1|[114,225,0]|
|key1|[113,226,0]|
|key1|[117,228,1]|
|key2|[118,229,1]|
+----+-----------+
最后,如果您确实需要RDD,则可以使用以下方法转换数据框:
result.rdd.map(row => row.getAs[String](0) -> row.getAs[(Int, Int, Int)](1))