Action 和 Transformation

Spark 中的操作指令

在 Spark 中,有兩個特殊的指令: Action 和 Transformation,其中,若是以 hadoop 中的 MapReduce 架構來說明,Map 屬於 Transformations,將資料發散到平行執行序中運算,而 Reduce 是 Actions,將平行處理的資料收回,進行運算,定義如下:

  • map (func): Return a new distributed dataset formed by passing each element of the source through a function func.

  • reduce (func): Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.

但和 hadoop 不同,Spark 中,不只有兩種運算,而是將運算分成兩個類別,對應於對於 RDD 的不同處理。我們先列出官方指南中的介紹:

  • transformations, which create a new dataset from an existing one

  • actions, which return a value to the driver program after running a computation on the dataset.

在 Spark 中,Transformations 本身不會主動被執行,只有在相對應的 Actions 執行時,才會進行。這樣的特性和 hadoop 中的 MapReduce 並不相同,在hadoop 中 Map 和 Reduce 視為兩種不同映射函數,並無執行上的從屬關係 (當然,Map 的結果仍要 Reduce 來回收)。

Spark 架構改變大概是因為多階段平行運算架構的支援,像是下圖的平行架構:

考慮到不同平行階段不一定同步,我們需要同步的查核點,來確保不同 "階段",此時,Actions (也就是 hadoop 中的 Reduce),就扮演了這樣的角色。 而更多的 Actions 和 Transformations,可以分別參考:

Last updated