1. 程式人生 > >在Spark Shell中編寫WordCount程式

在Spark Shell中編寫WordCount程式

Spark Shell是一個互動式的命令列,裡面可以寫Spark程式(Scala語言),也是一個客戶端,用於提交Spark程式

1.啟動Spark Shell

bin/spark-shell

 上邊是沒有指定Master地址的啟動方式,啟動後用的是spark的local模式執行的,是模擬了spark叢集執行的過程

bin/spark-shell --master spark://cdh0:7077,cdh1:7077 

上邊是指定了Master地址的啟動方式,會將任務提交到叢集,這時候使用jps檢視,可以看到機器上的SparkSubmit和CoarseGrainedExecutorBackend程序都已經存在了,SparkSubmit會連線Master,並申請計算資源,然後Master進行資源排程(讓Worker來啟動Executor)

2.向hdfs中上傳一個用來測試的資料檔案

例如:   test.txt

hdfs yarn
hadoop hdfs
yarn mapreduce
hadoop yarn
hdfs mapreduce

然後上傳到hdfs中

3.在Spark Shell中編寫WordCount程式

在Spark Shell中使用Scala編寫Spark程式

sc.textFile("hdfs://cdh0:8020/usr/ys/input/test.txt").flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).saveAsTextFile("hdfs://cdh0:8020/usr/output")

引數說明:

sc是SparkContext物件,該物件是提交spark程式的入口

textFile("hdfs://cdh0:8020/usr/ys/input/test.txt")是向hdfs中讀取資料

flatMap(_.split(" "))是先map後進行扁平化操作

map((_,1))是將單詞和1構成元組

reduceByKey(_+_)是按照key進行reduce,並將value累加

saveAsTextFile("hdfs://cdh0:8020/usr/output2")是儲存到hdfs的目錄中

4.在hdfs中檢視結果

bin/hdfs dfs -cat /usr/output/*