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这两个集合.不仅从根本上为一些问题提供了解决方 ...
随机推荐
- Redis-缓存穿透、缓存雪崩、缓存击穿、缓存一致性、并发竞争
缓存流程 在讲这五个问题之前,首先我们回顾下正常的缓存的使用流程 程序在处理请求时,会先从缓存中进行查询,如果缓存中没有对应的key,则会从数据库中查询,如果查询到结果,并将查询结果添加到缓存中去,反 ...
- JS中使用FormData上传图片
<!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...
- playbooks框架与子文件编写规范
Test Playbooks框架 详细目录testenv文件 主任务文件main.yml 任务入口文件deploy.yml Ansible连接playbooks需要添加ssh协议认证 ...
- Django HttpResponse、render、redirect
一.HttpResponse 作业:返回相应的内容 格式: return HttpResponse("Hello, World") 二.render 作业:提交网页和字符串替换 提 ...
- 12.instanceof和类型转换
Instanceof: 判断一个对象是什么类型的~,可以判断两个类之间是否存在父子关系 package com.oop.demo07; public class Person { public voi ...
- 【模板】2-SAT问题
问题简述 有 \(n\) 个变量,每个变量可赋为 \(1\) 或 \(0\) 必须满足一些限制条件,如" \(a\) 为1 或 \(b\) 为0 " " \(a\) 为0 ...
- 正斜杠(" / ")和反斜杠(" \ ")的区别
反斜杠“\”是电脑出现了之后为了表示程序设计里的特殊含义才发明的专用标点.所以除了程序设计领域外,任何地方都不应该使用反斜杠. 如何区分正反斜杠 英语:"/" 英文是forward ...
- Frameworks.Entity.Core 4
Project.Core\Frameworks.Entity.Core\Commons\ 1 AutoMapperExtension.cs AutoMapper扩展方法 2枚举类型扩展方法EnumEx ...
- hadoop中两种上传文件方式
记录如何将本地文件上传至HDFS中 前提是已经启动了hadoop成功(nodedate都成功启动) ①先切换到HDFS用户 ②创建一个user件夹 bin/hdfs dfs -mkdir /user ...
- 完美实现STM32单总线挂多个DS18B20
一般常见的STM32的关于DS18B20的例程都是检测一个传感器,代码一般都是跳过ROM检测,直接获取温度值.这种写法并不适用于单总线上挂载多个DS18B20的情况,Sandeepin的这个代码就是针 ...