Spark算子 - aggregateByKey

釋義:

  1. aggregateByKey邏輯類似 aggregate,但 aggregateByKey針對的是PairRDD,即鍵值對 RDD,所以返回結果也是 PairRDD,結果形式爲:(各個Key, 同樣Key對應的Value聚合後的值)。
  2. aggregateByKey先將每個partition內元素進行分組計算,然後將每個partition的計算結果進行combine,得到最終聚合結果。且最終結果允許跟原始RDD類型不同
    方法簽名如下:
def aggregateByKey[U: ClassTag](zeroValue: U)(seqOp: (U, V) => U, combOp: (U, U) => U): RDD[(K, U)] = self.withScope {
    ...
}

案例:

統計單詞個數 WordCount

object TestAggregateByKey {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession.builder().appName("MyApp").master("local[1]").getOrCreate()
    val data = Array("hello world", "simple app is good", "good world")
    val result: Array[(String, Int)] = spark.sparkContext.parallelize(data, 1)
      .flatMap(_.split(" "))
      .map((_, 1))
      .aggregateByKey(0)(
        (cnt1: Int, cnt2: Int) => cnt1 + cnt2,
        (partitionAllCnt1: Int, partitionAllCnt2: Int) => partitionAllCnt1 + partitionAllCnt2
      )
      .collect()
    result.foreach(println)
  }
}

輸出:

(is,1)
(app,1)
(simple,1)
(hello,1)
(good,2)
(world,2)

解釋:

  1. 先將每個詞map成 (詞語, 1)的形式
  2. 調用aggregateByKey之後,每個partition內已經按key進行分組了,之後傳入初始值0作爲每個組的個數,接着進行 cnt1 + cnt2,就是同個key內進行1+1操作,比如單詞good 有兩個value都是1,此時單詞good的組內,計算的值即爲2
  3. 所有partition的結果進行計算



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章