剛開始看Spark API 或者Scala編程的時(shí)候,發(fā)現(xiàn)函數(shù)式編程看的不太明白。又不想系統(tǒng)的看看Scala的書,就找找網(wǎng)上資料了,順便做做筆記。
map
map操作,按照Spark里面的說就是,將一個(gè)RDD中的每一個(gè)元素都執(zhí)行一個(gè)指定的函數(shù),產(chǎn)生一個(gè)新的RDD,兩個(gè)RDD中的元素一 一對(duì)應(yīng),除此之外,生成新的RDD與原來的RDD分區(qū)個(gè)數(shù)一樣。
- map(x => x2):x => x2 是一個(gè)函數(shù),x是傳入?yún)?shù)即RDD的每個(gè)元素,x*2是返回值
- map(x => (x,1)): 該函數(shù)將RDD的每個(gè)元素(例如:a,b,c...)變?yōu)?(a,1),(b,1),(c,1)...鍵值對(duì)的形式
- map(x => x.split("\s+")): 該函數(shù)以行為分割,將每行變?yōu)橐粋€(gè)array。
scala> val test1 = sc.parallelize(1 to 9) //默認(rèn)分區(qū)數(shù)來創(chuàng)建一個(gè)RDD
test1: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at parallelize at <console>:24
scala> test1.collect //查看一下test1的內(nèi)容
res2: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> val test2 = test1.map(x=>(x*2))// Int類型的每個(gè)元素乘以2
test3: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[2] at map at <console>:26
scala> test2.collect
res8: Array[Int] = Array(2, 4, 6, 8, 10, 12, 14, 16, 18)
scala> val test3 = test1.map(x => (x,"one"))//每個(gè)元素后加上一個(gè)字符串“one”,變成鍵值對(duì)。
test4: org.apache.spark.rdd.RDD[(Int, String)] = MapPartitionsRDD[3] at map at <console>:26
scala> test3.collect
res10: Array[(Int, String)] = Array((1,one), (2,one), (3,one), (4,one), (5,one), (6,one), (7,one), (8,one), (9,one))
//查看HDFS 中的數(shù)據(jù)
Spark@master:~/hadoop-2.7.0/sbin$ hadoop fs -text /test/hello.txt
hello world
nihao a
ni zai gan ma
hello tom
hello jeey
ni zai na
scala> val test4 = sc.textFile("/test/hello.txt")//從HDFS中讀取數(shù)據(jù)
test4: org.apache.spark.rdd.RDD[String] = /test/hello.txt MapPartitionsRDD[5] at textFile at <console>:24
scala> test4.map(line => line.split("\\s+")).collect
res12: Array[Array[String]] = Array(Array(hello, world), Array(nihao, a), Array(ni, zai, gan, ma), Array(hello, tom), Array(hello, jeey), Array(ni, zai, na), Array(""))
flatMap
flatMap與map有些類似,卻別是map將原RDD中的每個(gè)元素處理后只生成一個(gè)新的元素,而flatMap卻可以生成多個(gè)元素,還是用上面的數(shù)據(jù),做一下對(duì)比。
scala> test4.flatMap(line => line.split("\\s+")).collect
res18: Array[String] = Array(hello, world, nihao, a, ni, zai, gan, ma, hello, tom, hello, jeey, ni, zai, na, "")
distinct
distinct去掉重復(fù)的元素
scala> test4.flatMap(line => line.split("\\s+")).distinct.collect
res24: Array[String] = Array(ma, a, tom, zai, "", jeey, hello, gan, ni, na, nihao, world)
mapPartitons
map輸入是RDD中的每一個(gè)元素,而mapPartitons輸入是RDD中的每個(gè)分區(qū)的迭代器,mapPartitions比map高效。
其他
- union返回兩個(gè)RDD的合并,返回元素不去重。
rdd1.unior(rdd2)
參考
圖解Spark核心技術(shù)與案例實(shí)戰(zhàn)