spark數據集操作

 

首先將一行映射爲整數值,從而創建一個新的數據集。reduce在該數據集上調用以查找最大字數。

scala> textFile.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)
res4: Long = 15

我們可以輕鬆調用其他地方聲明的函數。我們將使用Math.max()函數使這段代碼更容易理解:

scala> import java.lang.Math
import java.lang.Math

scala> textFile.map(line => line.split(" ").size).reduce((a, b) => Math.max(a, b))
res5: Int = 15

一種常見的數據流模式是MapReduce。Spark可以輕鬆實現MapReduce流程:

scala> val wordCounts = textFile.flatMap(line => line.split(" ")).groupByKey(identity).count()
wordCounts: org.apache.spark.sql.Dataset[(String, Long)] = [value: string, count(1): bigint]

在這裏,調用flatMap將行數據集轉換爲單詞數據集,然後組合groupByKeycount計算文件中的單詞計數作爲(字符串,長整數)對的數據集。要在我們的shell中收集單詞count,我們可以調用collect

scala> wordCounts.collect()
res6: Array[(String, Int)] = Array((means,1), (under,2), (this,3), (Because,1), (Python,2), (agree,1), (cluster.,1), ...)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章