在 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屋!
查看全文