在Spark中的RDD中的邻居元素上操作 [英] Operate on neighbor elements in RDD in Spark
本文介绍了在Spark中的RDD中的邻居元素上操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个收藏夹:
List(1, 3,-1, 0, 2, -4, 6)
很容易将其排序为:
List(-4, -1, 0, 1, 2, 3, 6)
然后我可以通过计算6-3、3-2、2-1、1-0等来构造一个新的集合,如下所示:
Then I can construct a new collection by compute 6 - 3, 3 - 2, 2 - 1, 1 - 0, and so on like this:
for(i <- 0 to list.length -2) yield {
list(i + 1) - list(i)
}
并获得向量:
Vector(3, 1, 1, 1, 1, 3)
也就是说,我要使下一个元素减去当前元素.
That is, I want to make the next element minus the current element.
但是如何在Spark的RDD中实现呢?
But how to implement this in RDD on Spark?
我知道该收藏:
List(-4, -1, 0, 1, 2, 3, 6)
集合中会有一些分区,每个分区都是有序的,我可以在每个分区上执行类似的操作,然后一起在每个分区上收集结果吗?
There will be some partitions of the collection, each partition is ordered, can I do the similar operation on each partition and collect results on each partition together?
推荐答案
最有效的解决方案是使用sliding
方法:
The most efficient solution is to use sliding
method:
import org.apache.spark.mllib.rdd.RDDFunctions._
val rdd = sc.parallelize(Seq(1, 3,-1, 0, 2, -4, 6))
.sortBy(identity)
.sliding(2)
.map{case Array(x, y) => y - x}
这篇关于在Spark中的RDD中的邻居元素上操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文