groupByKey
源码
/**
* 将RDD的每个key的values分组为一个单独的序列,并且每个组内的元素的排序不定
*
* @note groupByKey很消耗资源,如果要对每个Key的values进行聚合(比如求和或平均值),
* 用 `aggregateByKey`或者`reduceByKey` 代替,将会更节省性能。
*
* @note 在当前实现的情况下,groupByKey必须能够在内存中保存所有(K,V)对,
* 如果一个key的values太多,将会产生OutOfMemoryError
*/
def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = self.withScope {
// groupByKey不应该使用map side combine ,mapSideCombine = false
// 因为map side combine 并不会减少数据的shuffle次数,
// 并且要求将map side 的数据放入一张hash表中,导致 old gen中有更多的对象;
val createCombiner = (v: V) => CompactBuffer(v)
val mergeValue = (buf: CompactBuffer[V], v: V) => buf += v
val mergeCombiners = (c1: CompactBuffer[V], c2: CompactBuffer[V]) => c1 ++= c2
val bufs = combineByKeyWithClassTag[CompactBuffer[V]](
createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false)
bufs.asInstanceOf[RDD[(K, Iterable[V])]]
}
def groupByKey(): RDD[(K, Iterable[V])]
def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])]
def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])]
Java案例
public static void groupByKey() {
SparkConf conf = new SparkConf().setAppName("groupByKey").setMaster("local");
JavaSparkContext sc = new JavaSparkContext(conf);
List<Tuple2<String, Integer>> scoreList = Arrays.asList(
new Tuple2<<