Spark算子:RDD基本转换操作(4)–union、intersection、subtract

时间:2022-12-19 20:46:57

union

def union(other: RDD[T]): RDD[T]

该函数比较简单,就是将两个RDD进行合并,不去重

 

 
 
  1. scala> var rdd1 = sc.makeRDD(1 to 2,1)
  2. rdd1: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[45] at makeRDD at :21
  3.  
  4. scala> rdd1.collect
  5. res42: Array[Int] = Array(1, 2)
  6.  
  7. scala> var rdd2 = sc.makeRDD(2 to 3,1)
  8. rdd2: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[46] at makeRDD at :21
  9.  
  10. scala> rdd2.collect
  11. res43: Array[Int] = Array(2, 3)
  12.  
  13. scala> rdd1.union(rdd2).collect
  14. res44: Array[Int] = Array(1, 2, 2, 3)
  15.  

intersection

def intersection(other: RDD[T]): RDD[T]
def intersection(other: RDD[T], numPartitions: Int): RDD[T]
def intersection(other: RDD[T], partitioner: Partitioner)(implicit ord: Ordering[T] = null): RDD[T]

该函数返回两个RDD的交集,并且去重
参数numPartitions指定返回的RDD的分区数。
参数partitioner用于指定分区函数

 
 
  1. scala> var rdd1 = sc.makeRDD(1 to 2,1)
  2. rdd1: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[45] at makeRDD at :21
  3.  
  4. scala> rdd1.collect
  5. res42: Array[Int] = Array(1, 2)
  6.  
  7. scala> var rdd2 = sc.makeRDD(2 to 3,1)
  8. rdd2: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[46] at makeRDD at :21
  9.  
  10. scala> rdd2.collect
  11. res43: Array[Int] = Array(2, 3)
  12.  
  13. scala> rdd1.intersection(rdd2).collect
  14. res45: Array[Int] = Array(2)
  15.  
  16. scala> var rdd3 = rdd1.intersection(rdd2)
  17. rdd3: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[59] at intersection at :25
  18.  
  19. scala> rdd3.partitions.size
  20. res46: Int = 1
  21.  
  22. scala> var rdd3 = rdd1.intersection(rdd2,2)
  23. rdd3: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[65] at intersection at :25
  24.  
  25. scala> rdd3.partitions.size
  26. res47: Int = 2
  27.  
  28.  

subtract

def subtract(other: RDD[T]): RDD[T]
def subtract(other: RDD[T], numPartitions: Int): RDD[T]
def subtract(other: RDD[T], partitioner: Partitioner)(implicit ord: Ordering[T] = null): RDD[T]

该函数类似于intersection,但返回在RDD中出现,并且不在otherRDD中出现的元素,不去重
参数含义同intersection

 
 
  1. scala> var rdd1 = sc.makeRDD(Seq(1,2,2,3))
  2. rdd1: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[66] at makeRDD at :21
  3.  
  4. scala> rdd1.collect
  5. res48: Array[Int] = Array(1, 2, 2, 3)
  6.  
  7. scala> var rdd2 = sc.makeRDD(3 to 4)
  8. rdd2: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[67] at makeRDD at :21
  9.  
  10. scala> rdd2.collect
  11. res49: Array[Int] = Array(3, 4)
  12.  
  13. scala> rdd1.subtract(rdd2).collect
  14. res50: Array[Int] = Array(1, 2, 2)
  15.  

转载请注明:lxw的大数据田地 » Spark算子:RDD基本转换操作(4)–union、intersection、subtract