SparkContext創建
val conf = new SparkConf().setAppName("AppName")
val sc = new SparkContext(conf)
讀取Hdfs文件
sc.textFile(path)
textFile的參數是一個path,這個path可以是:
1. 一個文件路徑,這時候只裝載指定的文件
2. 一個目錄路徑,這時候只裝載指定目錄下面的所有文件(不包括子目錄下面的文件)
3. 通過通配符的形式加載多個文件或者加載多個目錄下面的所有文件
4.在path前面加上file:// 表示從本地文件系統讀,在path前面加上hdfs://表示從hdfs文件系統上讀,默認是從hdfs讀取文件
保存文件
saveAsTextFile(path)
def saveAsTextFile(path: String): Unit
def saveAsTextFile(path: String, codec: Class[_ <: CompressionCodec]): Unit
saveAsTextFile用於將RDD以文本文件的格式存儲到文件系統中。
codec參數可以指定壓縮的類名。
saveAsTextFile("hdfs:///tmp/test/",classOf[com.hadoop.compression.lzo.LzopCodec])
在path前面加上file:// 表示從本地文件系統讀,在path前面加上hdfs://表示從hdfs文件系統上讀,默認是從hdfs讀取文件
Spark算子分類及功能
Value型Transformation算子
輸入分區與輸出分區一對一型
map
flatMap
mapPartitions
glom
輸入分區與輸出分區多對一型
union
cartesian
輸入分區與輸出分區多對多型
groupBy
輸出分區爲輸入分區子集型
filter
distinct
subtract
sample
takeSample
Cache型
cache
persist
Key-Value型Transformation算子
輸入分區與輸出分區一對一
mapValues
對單個RDD或兩個RDD聚集
單個RDD聚集
combineByKey
reduceByKey
partitionBy
對兩個RDD進行聚集
cogroup
連接
join
leftOutJoin和rightOutJoin
Actions算子
無輸出
foreach
HDFS
saveAsTextFile
saveAsObjectFile
Scala集合和數據類型
collect
collectAsMap
reduceByKeyLocally
lookup
count
top
reduce
fold
aggregate