本文介紹了Spark中map(func)和flatMap(func)這兩個函數的區別及具體使用。
函數原型
1.map(func)
將原數據的每個元素傳給函數func進行格式化,返回一個新的分佈式數據集。(原文:Return a new distributed dataset formed by passing each element of the source through a function func.)
2.flatMap(func)
跟map(func)類似,但是每個輸入項和成為0個或多個輸出項(所以func函數應該返回的是一個序列化的數據而不是單個數據項)。(原文:Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).)
使用說明
在使用時map會將一個長度為N的RDD轉換為另一個長度為N的RDD;而flatMap會將一個長度為N的RDD轉換成一個N個元素的集合,然後再把這N個元素合成到一個單個RDD的結果集。
比如一個包含三行內容的數據文件「README.md」。
a b c
d
經過以下轉換過程
val textFile = sc.textFile("README.md")
textFile.flatMap(_.split(" "))
其實就是經歷了以下轉換
["a b c", "", "d"] => [["a","b","c"],[],["d"]] => ["a","b","c","d"]
在這個示例中,flatMap就把包含多行數據的RDD,即[「a b c」, 「」, 「d」] ,轉換為了一個包含多個單詞的集合。實際上,flatMap相對於map多了的是[[「a」,」b」,」c」],[],[「d」]] => [「a」,」b」,」c」,」d」]這一步。
區別對比
map(func)函數會對每一條輸入進行指定的func操作,然後為每一條輸入返回一個對象;而flatMap(func)也會對每一條輸入進行執行的func操作,然後每一條輸入返回一個相對,但是最後會將所有的對象再合成為一個對象;從返回的結果的數量上來講,map返回的數據對象的個數和原來的輸入數據是相同的,而flatMap返回的個數則是不同的。請參考下圖進行理解:
通過上圖可以看出,flatMap其實比map多的就是flatten操作。
示例驗證
接下來,我們用一個例子來進行比較,首先在HDFS里寫入了這樣內容的一個文件:
C:\WINDOWS\system32>hadoop fs -cat hdfs://localhost:9000/user/input/wordcount.txt
word in text
hello spark
the third line
C:\WINDOWS\system32>
然後再spark里進行測試,如下
scala> var textFile =sc.textFile("hdfs://localhost:9000/user/input/wordcount.txt")
textFile: org.apache.spark.rdd.RDD[String] = hdfs://localhost:9000/user/input/wordcount.txt MapPartitionsRDD[1] at textFile at :27
map的結果
scala> var mapResult = textFile.map(line => line.split("\\s+"))
mapResult: org.apache.spark.rdd.RDD[Array[String]] = MapPartitionsRDD[2] at map at :29
scala> mapResult.collect
res0: Array[Array[String]] = Array(Array(word, in, text), Array(hello, spark), Array(the, third, line))
flatMap的結果
scala> var flatMapResult = textFile.flatMap(line => line.split("\\s+"))
flatMapResult: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[3] at flatMap at :29
scala> flatMapResult.collect
res1: Array[String] = Array(word, in, text, hello, spark, the, third, line)
參考文章:
http://stackoverflow.com/questions/22350722/can-someone-explain-to-me-the-difference-between-map-and-flatmap-and-what-is-a-g;
http://spark.apache.org/docs/latest/programming-guide.html#transformations;
http://blog.csdn.net/samhacker/article/details/41927567;