Spark API 之 map、mapPartitions、mapValues、flatMap、flatMapValues详解
原文地址:https://blog.csdn.net/helloxiaozhe/article/details/80492933
1、创建一个RDD变量,通过help函数,查看相关函数定义和例子:
>>> a = sc.parallelize([(1,2),(3,4),(5,6)]) >>> a
ParallelCollectionRDD[21] at parallelize at PythonRDD.scala:475
>>> help(a.map) Help on RDD in module pyspark.rdd object: class RDD(__builtin__.object)
| A Resilient Distributed Dataset (RDD), the basic abstraction in Spark.
| Represents an immutable, partitioned collection of elements that can be
| operated on in parallel.
|
| Methods defined here:
|
| __add__(self, other)
| Return the union of this RDD and another one.
|
| >>> rdd = sc.parallelize([1, 1, 2, 3])
| >>> (rdd + rdd).collect()
| [1, 1, 2, 3, 1, 1, 2, 3]
RDD是什么?
RDD是Spark中的抽象数据结构类型,任何数据在Spark中都被表示为RDD。从编程的角度来看,RDD可以简单看成是一个数组。和普通数组的区别是,RDD中的数据是分区存储的,这样不同分区的数据就可以分布在不同的机器上,同时可以被并行处理。因此,Spark应用程序所做的无非是把需要处理的数据转换为RDD,然后对RDD进行一系列的变换和操作从而得到结果。
2、map(function)
map是对RDD中的每个元素都执行一个指定的函数来产生一个新的RDD。任何原RDD中的元素在新RDD中都有且只有一个元素与之对应。
map(self, f, preservesPartitioning=False) method of pyspark.rdd.RDD instance
Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)]
3、mapPartitions(function)
map()的输入函数是应用于RDD中每个元素,而mapPartitions()的输入函数是应用于每个分区
mapPartitions是map的一个变种。map的输入函数是应用于RDD中每个元素,而mapPartitions的输入函数是应用于每个分区,也就是把每个分区中的内容作为整体来处理的。
mapPartitions(self, f, preservesPartitioning=False) method of pyspark.rdd.RDD instance
Return a new RDD by applying a function to each partition of this RDD. >>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7]
4、mapValues(function)
原RDD中的Key保持不变,与新的Value一起组成新的RDD中的元素。因此,该函数只适用于元素为KV对的RDD。
mapValues(self, f) method of pyspark.rdd.RDD instance
Pass each value in the key-value pair RDD through a map function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["apple", "banana", "lemon"]), ("b", ["grapes"])])
>>> def f(x): return len(x)
>>> x.mapValues(f).collect()
[('a', 3), ('b', 1)]
5、flatMap(function)
与map类似,区别是原RDD中的元素经map处理后只能生成一个元素,而原RDD中的元素经flatmap处理后可生成多个元素
Help on method flatMap in module pyspark.rdd: flatMap(self, f, preservesPartitioning=False) method of pyspark.rdd.RDD instance
Return a new RDD by first applying a function to all elements of this
RDD, and then flattening the results. >>> rdd = sc.parallelize([2, 3, 4])
>>> sorted(rdd.flatMap(lambda x: range(1, x)).collect())
[1, 1, 1, 2, 2, 3]
>>> sorted(rdd.flatMap(lambda x: [(x, x), (x, x)]).collect())
[(2, 2), (2, 2), (3, 3), (3, 3), (4, 4), (4, 4)]
6、flatMapValues(function)
flatMapValues类似于mapValues,不同的在于flatMapValues应用于元素为KV对的RDD中Value。每个一元素的Value被输入函数映射为一系列的值,然后这些值再与原RDD中的Key组成一系列新的KV对。
flatMapValues(self, f) method of pyspark.rdd.RDD instance
Pass each value in the key-value pair RDD through a flatMap function
without changing the keys; this also retains the original RDD's
partitioning.
>>> x = sc.parallelize([("a", ["x", "y", "z"]), ("b", ["p", "r"])])
>>> def f(x): return x
>>> x.flatMapValues(f).collect()
[('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')]
7、reduce函数
reduce将RDD中元素两两传递给输入函数,同时产生一个新的值,新产生的值与RDD中下一个元素再被传递给输入函数直到最后只有一个值为止。
reduce(self, f) method of pyspark.rdd.RDD instance
Reduces the elements of this RDD using the specified commutative and
associative binary operator. Currently reduces partitions locally. >>> from operator import add
>>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add)
15
>>> sc.parallelize((2 for _ in range(10))).map(lambda x: 1).cache().reduce(add)
10
>>> sc.parallelize([]).reduce(add)
Traceback (most recent call last):
...
ValueError: Can not reduce() empty RDD
例子如下:
>>> from operator import add
>>> b.collect()
[1, 2, 3, 4, 5, 6]
>>> b.reduce(add) # 引入内置函数
21
>>> b.reduce(lambda a,b:a+b) # lambda自定义的匿名函数
21
8、reduceByKey函数
顾名思义,reduceByKey就是对元素为KV对的RDD中Key相同的元素的Value进行reduce,因此,Key相同的多个元素的值被reduce为一个值,然后与原RDD中的Key组成一个新的KV对。
Help on method reduceByKey in module pyspark.rdd: reduceByKey(self, func, numPartitions=None, partitionFunc=<function portable_hash>) method of pyspark.rdd.RDD instance
Merge the values for each key using an associative and commutative reduce function. This will also perform the merging locally on each mapper before
sending results to a reducer, similarly to a "combiner" in MapReduce. Output will be partitioned with C{numPartitions} partitions, or
the default parallelism level if C{numPartitions} is not specified.
Default partitioner is hash-partition. >>> from operator import add
>>> rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])
>>> sorted(rdd.reduceByKey(add).collect())
[('a', 2), ('b', 1)]
Spark API 之 map、mapPartitions、mapValues、flatMap、flatMapValues详解的更多相关文章
- .Net for Spark 实现 WordCount 应用及调试入坑详解
.Net for Spark 实现WordCount应用及调试入坑详解 1. 概述 iNeuOS云端操作系统现在具备物联网.视图业务建模.机器学习的功能,但是缺少一个计算平台产品.最近在调研使用 ...
- 58、Spark Streaming: DStream的output操作以及foreachRDD详解
一.output操作 1.output操作 DStream中的所有计算,都是由output操作触发的,比如print().如果没有任何output操作,那么,压根儿就不会执行定义的计算逻辑. 此外,即 ...
- [spark]-Spark2.x集群搭建与参数详解
在前面的Spark发展历程和基本概念中介绍了Spark的一些基本概念,熟悉了这些基本概念对于集群的搭建是很有必要的.我们可以了解到每个参数配置的作用是什么.这里将详细介绍Spark集群搭建以及xml参 ...
- 大数据学习系列之七 ----- Hadoop+Spark+Zookeeper+HBase+Hive集群搭建 图文详解
引言 在之前的大数据学习系列中,搭建了Hadoop+Spark+HBase+Hive 环境以及一些测试.其实要说的话,我开始学习大数据的时候,搭建的就是集群,并不是单机模式和伪分布式.至于为什么先写单 ...
- 对于maven创建spark项目的pom.xml配置文件(图文详解)
不多说,直接上干货! http://mvnrepository.com/ 这里,怎么创建,见 Spark编程环境搭建(基于Intellij IDEA的Ultimate版本)(包含Java和Scala版 ...
- Spark源码系列(二)RDD详解
1.什么是RDD? 上一章讲了Spark提交作业的过程,这一章我们要讲RDD.简单的讲,RDD就是Spark的input,知道input是啥吧,就是输入的数据. RDD的全名是Resilient Di ...
- Spark Structured Streaming框架(4)之窗口管理详解
1. 结构 1.1 概述 Structured Streaming组件滑动窗口功能由三个参数决定其功能:窗口时间.滑动步长和触发时间. 窗口时间:是指确定数据操作的长度: 滑动步长:是指窗口每次向前移 ...
- Spark 系列(四)—— RDD常用算子详解
一.Transformation spark 常用的 Transformation 算子如下表: Transformation 算子 Meaning(含义) map(func) 对原 RDD 中每个元 ...
- SE6新特性之集合Set、Map、WeakSet和WeakMap详解
SE5的时候我们经常用数组或者类数组对象来操作数据,而对于一些使用惯了java之类语言的集合的开发人员来说,总有少了点什么的感觉,SE6提供Set和Map这两个集合.不仅从根本上为一些问题提供了解决方 ...
随机推荐
- 异步-promise、async、await
下面代码打印结果是? setTimeout(()=>{ console.log(1) }) new Promise((resolve,reject)=>{ console.log(2) r ...
- Magicodes.IE之Excel模板导出教材订购表
说明 本教程主要说明如果使用Magicodes.IE.Excel完成教材订购表的Excel模板导出. 要点 本教程使用Magicodes.IE.Excel来完成Excel模板导出 需要通过创建Dto来 ...
- vue将接口返回的日期实时转换为几分钟前、几小时前、几天前
项目开发中,各种需求都会遇到,有些需求很合理,也好实现,有些需求不能说不合理,就是太麻烦,就比如类似标题所描述这种的需求,你不能说它是不合理的需求,因为很多论坛或微博.朋友圈.QQ空间之类的这种效果还 ...
- 恕我直言,牛逼哄哄的MongoDB你可能只会30%
MongoDB闪亮登场 自我介绍 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库 ...
- 微信授权流程和JSSDK调用流程
概念理解 业务域名:当前业务使用的是哪个网站,好处:设置业务域名后,在微信内访问该域名下页面时,不会被重新排版.不出现“防欺诈盗号,请误支付或输入qq密码”的提示,微信认为该域名是安全的,客户也不觉得 ...
- npm 安装出现 run `npm audit fix` to fix them, or `npm audit` for details 解决办法
1.npm audit fix 2. npm audit fix --force 3.npm audit 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链 ...
- .NET编程周记第3期-2020年1月19日
整理了2020年1月19日这周阅读的几篇有趣的和.NET开发相关的文章.在这里和大家分享. 0x00 Introducing Nullable Reference Types in C# 如标题所示, ...
- Flask路由+视图补充
一.路由设置的两种方法 1.装饰器 @app.route('/index/') def index(): return 'Hello World!' 2.源码 route->decorator- ...
- Hibernate定制Tuplizer
Hibernate定制Tuplizer,使用@Tuplizer注解 本文转自http://www.521100.net/hibernate-tuplizer.html 首先,第一步在Hinbernat ...
- python,finally的应用
脚本执行过程中可能因为被测试的环境有改变导致中间某一部分无法继续执行下去 可以在最后一行加上finally来执行最后一句脚本 比如 最后执行退出 表示 无论中间过程失败还是成功,最终都会执行退出操作 ...