1.5.1.4 常用算子之map/flatmap/mapPartitions/glom算子

总目录:https://blog.csdn.net/qq_41106844/article/details/105553392

Hadoop - 子目录:https://blog.csdn.net/qq_41106844/article/details/105553369

输入分区与输出分区一对一型

  • map算子
     将原来 RDD 的每个数据项通过 map 中的用户自定义函数 f 映射转变为一个新的元素。源码中 map 算子相当于初始化一个 RDD, 新 RDD 叫做 MappedRDD。
    这个函数的用法和Python自带的map函数一样。
 
20155953-3ed692d87f027598.png
map

pyspark实现

>>> rdd = sc.parallelize([1,2,3,4])  
>>> rdd.getNumPartitions()  //查看分区数
1
>>> rdd1 = rdd.map(lambda i : range(1,i)) //将rdd内每个元素依次放入map中的函数内获取返回值。
>>> rdd1.collect()
[range(1, 1), range(1, 2), range(1, 3), range(1, 4)]

scala实现

scala> val data = sc.parallelize(1 to 10)
data: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[0] at parallelize at <console>:24

scala> val result = data.map(it => it + 1)
result: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[1] at map at <console>:25

scala> result.collect
res0: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)  
  • flatmap算子
    将原来 RDD 中的每个元素通过函数 f 转换为新的元素,并将生成的 RDD 的每个集合中的元素合并为一个集合,内部创建 FlatMappedRDD。
 
20155953-f9cfd9c4f1f52e68.png
flatmap

他和map的区别是会打通不同的分区,一般用于读取文件。

pyspark实现

>>> rdd = sc.parallelize([1,2,3,4])  
>>> rdd2 = rdd.flatMap(lambda i:range(1,i))
>>> rdd2.collect()
[1, 1, 2, 1, 2, 3]

scala实现

scala> val result2 = data.filter(it => it%2 == 0 )
result2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[3] at filter at <console>:25

scala> result2.collect
res1: Array[Int] = Array(2, 4, 6, 8, 10)
  • mapPartitions算子
    mapPartitions 函 数 获 取 到 每 个 分 区 的 迭 代器,在 函 数 中 通 过 这 个 分 区 整 体 的 迭 代 器 对整 个 分 区 的 元 素 进 行 操 作。 内 部 实 现 是 生 成MapPartitionsRDD。

     
     
    20155953-13810ea04f4d71af.png
    mapPartitions
  • glom算子
     glom函数将每个分区形成一个数组,内部实现是返回的GlommedRDD。

     
     
    20155953-7ca497c60cf8e609.png
    glom

pyspark实现

>>> rdd.glom().collect()
[[1, 2, 3, 4]]
// 如果是两个分区的RDD,这里就是一个二维列表。
发布了242 篇原创文章 · 获赞 60 · 访问量 2182

猜你喜欢

转载自blog.csdn.net/qq_41106844/article/details/105553350