reduceByKey和groupByKey的区别

Posted 0xcafedaddy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了reduceByKey和groupByKey的区别相关的知识,希望对你有一定的参考价值。

先来看一下在reduceByKey和groupByKey的源码,在PairRDDFunctions.scala文件中
/**
 * Merge the values for each key using an associative reduce function. This will also perform
 * the merging locally on each mapper before sending results to a reducer, similarly to a
 * "combiner" in MapReduce. Output will be hash-partitioned with the existing partitioner/
 * parallelism level.
 */
def reduceByKey(func: (V, V) => V): RDD[(K, V)] = {
  reduceByKey(defaultPartitioner(self), func)
}


/**
 * Group the values for each key in the RDD into a single sequence. Allows controlling the
 * partitioning of the resulting key-value pair RDD by passing a Partitioner.
 * The ordering of elements within each group is not guaranteed, and may even differ
 * each time the resulting RDD is evaluated.
 *
 * Note: This operation may be very expensive. If you are grouping in order to perform an
 * aggregation (such as a sum or average) over each key, using [[PairRDDFunctions.aggregateByKey]]
 * or [[PairRDDFunctions.reduceByKey]] will provide much better performance.
 *
 * Note: As currently implemented, groupByKey must be able to hold all the key-value pairs for any
 * key in memory. If a key has too many values, it can result in an [[OutOfMemoryError]].
 */
def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = {
  // groupByKey shouldn‘t use map side combine because map side combine does not
  // reduce the amount of data shuffled and requires all map side data be inserted
  // into a hash table, leading to more objects in the 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 = combineByKey[CompactBuffer[V]](
    createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine=false)
  bufs.asInstanceOf[RDD[(K, Iterable[V])]]
}
 

 

以上是关于reduceByKey和groupByKey的区别的主要内容,如果未能解决你的问题,请参考以下文章

reducebykey和groupbykey的区别

Spark中reduceByKey()和groupByKey()的区别

在Spark中关于groupByKey与reduceByKey的区别

Spark 中 RDD 算子 ReduceByKey 和 GroupByKey 使用方法和区别

Spark中groupBy groupByKey reduceByKey的区别

reduceByKey 与 groupByKey 与 aggregateByKey 与 combineByKey 之间的火花差异