spark3.0教程:RDD转换算子groupByKey()

说明

根据 key 进行分组,将相同 key 的value分到一组

groupBy() 的底层实现

要求: 源RDD 是 key-value 类型

返回:**key-value** 类型的 RDD,key是 源RDD中的key,value是集合

注意:打乱数据重组(shuffle操作)

声明

声明1

def groupByKey(): RDD[(K, Iterable[V])]

声明2

def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])]

参数:

  • numPartitions:分区数量

声明3

def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])]

参数:

  • partitioner:可指定分区器

源码

底层调用 groupByKey() ,可以指定分区器

例子

val sparConf = new SparkConf().setMaster("local[*]").setAppName("RDD")
val sc = new SparkContext(sparConf)
val rdd = sc.makeRDD(List(("李雷",2),("韩梅梅",3),("李雷",3)))

val resRDD: RDD[(String, Iterable[Int])]=rdd.groupByKey()

resRDD.collect().foreach(println)
sc.stop()

执行结果:

(李雷,CompactBuffer(2, 3))
(韩梅梅,CompactBuffer(3))

原文出处:/show_1IX1MHHQaYET.html