Spark 变换与动作备忘与例子

首先安利一个学习网站:http://www.hubwiz.com/

组合

例子:
将每一行(成员)映射为一个整数值(单词数量),这获得了一个新的RDD。然后在 这个新的RDD上执行reduce动作,找到(返回)了单词数量最多的行。

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

动作

首先获得textFile后面的变量,后面的例子都会用到。

1
var tf = sc.textFile("README.md")

  • count:计数
    返回文件的总行数:

    1
    2
    scala> tf.count()
    res9: Long = 95
  • top:前N个记录
    可以指定一个排序函数来进行排序比较,不指定的话使用默认的ascii码进行记录排序
    示例:

    1
    2
    scala> var top2 = tf.top(2)
    top2: Array[String] = Array(will run the Pi example locally., supports general computation graphs for data analysis. It also supports a)

使用排序函数的例子:
暂无

  • max : 取值最大的记录
    1
    2
    scala> tf.max()
    res14: String = will run the Pi example locally.

使用排序函数的例子:
暂无

  • reduce : 归约RDD
    例子:使用匿名函数将所有记录连接起来构成一个字符串
    1
    2
    scala> textFile.reduce((a,b)=>a+b)
    res60:String = #Apache SparkSpake is a fast...

例子:请使用你创建的textFile变量,返回最长的单词。

1
2
3
4
5
6
7
scala> tf.reduce((a,b)=>a+b).reduce((a,b) => if(a.size>b.size) a else b)
<console>:30: error: value size is not a member of Char
tf.reduce((a,b)=>a+b).reduce((a,b) => if(a.size>b.size) a else b)
^

scala> tf.reduce((a,b)=>a+b).reduce((a,b) => if(a>b) a else b)
res35: Char = z

  • collect : 取出全部记录

变换

  • map 映射
  • filter 过滤
  • sample 采样
  • union 合并
  • intersection 相交
  • distinct 去重