[Spark_API]Transformation-reduceByKey()和aggregateByKey()
2017-05-10 17:24
495 查看
aggregateByKey()与reduceByKey()(两者都会调用combineByKey()),唯一不同的是aggregateByKey()你会给出一个初始值zeroValue.
之所以reduceByKey()更好,是由于它使用了MapReduce的combiner这个特征,比如在类似+,*的这类combiner函数计算中,由于元素的顺序都无关紧要,使得Spark能够在多个分区上聚合(reduce)数值。
然而aggregateByKey()会聚合一个特定键的值,聚合(combined)的结果可以是任何特定的对象类型。你必须确定这些值在分区内部如何聚合(同一个节点),以及你如何将不同区的结果聚合。ReduceByKey()是一个特殊的例子,特殊之处在于值聚合后的数据类型和值的类型相同,在分区内部聚合的操作和聚合不同分区结果的操作一样。
作为一个例子,假如你有一组数组
来确定最后聚合结果的类型为set。
之所以reduceByKey()更好,是由于它使用了MapReduce的combiner这个特征,比如在类似+,*的这类combiner函数计算中,由于元素的顺序都无关紧要,使得Spark能够在多个分区上聚合(reduce)数值。
然而aggregateByKey()会聚合一个特定键的值,聚合(combined)的结果可以是任何特定的对象类型。你必须确定这些值在分区内部如何聚合(同一个节点),以及你如何将不同区的结果聚合。ReduceByKey()是一个特殊的例子,特殊之处在于值聚合后的数据类型和值的类型相同,在分区内部聚合的操作和聚合不同分区结果的操作一样。
作为一个例子,假如你有一组数组
val pairs = sc.parallelize(Array(("a", 3), ("a", 1), ("b", 7), ("a", 5)))现在你想使用对于同一个键,对它所有的值进行加法聚合,在这个例子中,reduceByKey和aggregateByKey()是一样的。
val resReduce = pairs.reduceByKey(_ + _) //the same operation for everything resReduce.collect res3: Array[(String, Int)] = Array((b,7), (a,9)) //0 is initial value, _+_ inside partition, _+_ between partitions val resAgg = pairs.aggregateByKey(0)(_+_,_+_) resAgg.collect res4: Array[(String, Int)] = Array((b,7), (a,9))然而,假如你想要聚合的结果是同一个键的所有值的set,但值本身的数据类型是整数.在这个情况下,你只能使用aggregateByKey()
来确定最后聚合结果的类型为set。
import scala.collection.mutable.HashSet //the initial value is a void Set. Adding an element to a set is the first //_+_ Join two sets is the _++_ val sets = pairs.aggregateByKey(new HashSet[Int])(_+_, _++_) sets.collect res5: Array[(String, scala.collection.mutable.HashSet[Int])] =Array((b,Set(7)), (a,Set(1, 5, 3)))
相关文章推荐
- Spark RDD/Core 编程 API入门系列 之rdd案例(map、filter、flatMap、groupByKey、reduceByKey、join、cogroupy等)(四)
- [Spark--基础]--聚合操作-reduceByKey、combineBykey、groupBy和AggregateByKey
- Spark API 详解/大白话解释 之 reduce、reduceByKey
- Spark RDD中Transformation的combineByKey、reduceByKey,join详解
- spark2.x由浅入深深到底系列六之RDD api reduceByKey与foldByKey对比
- Spark API 之 reduce、reduceByKey 、 mapvalues
- Spark RDD/Core 编程 API入门系列之map、filter、textFile、cache、对Job输出结果进行升和降序、union、groupByKey、join、reduce、look
- Spark API 详解/大白话解释 之 reduce、reduceByKey
- 大数据Spark “蘑菇云”行动第40课:Spark编程实战之aggregateByKey、reduceByKey、groupByKey、sortByKey深度解密
- Spark RDD/Core 编程 API入门系列之map、filter、textFile、cache、对Job输出结果进行升和降序、union、groupByKey、join、reduce、lookup(一)
- Spark RDD/Core 编程 API入门系列 之rdd案例(map、filter、flatMap、groupByKey、reduceByKey、join、cogroupy等)(四)
- 【Spark Java API】Transformation(6)—aggregate、aggregateByKey
- 结合Spark源码分析, combineByKey, aggregateByKey, foldByKey, reduceByKey
- 【Spark Java API】Transformation(11)—reduceByKey、foldByKey
- Spark操作:Aggregate和AggregateByKey
- pair RDD groupByKey countByKey countByValue aggregateByKey reduceByKey 测试
- Spark:reduceByKey函数的用法
- 通过 “由对象V到对象C的转换” 来说明 Spark_Streaming api中 reduceByKey 与 combineByKey 注意事项
- 【Spark】Spark-reduceByKey-深入理解
- Spark中groupByKey与reduceByKey算子之间的区别