博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
图解Spark API
阅读量:7043 次
发布时间:2019-06-28

本文共 8584 字,大约阅读时间需要 28 分钟。

初识spark,需要对其API有熟悉的了解才能方便开发上层应用。本文用图形的方式直观表达相关API的工作特点,并提供了解新的API接口使用的方法。例子代码全部使用python实现。

1. 数据源准备

准备输入文件:

$ cat /tmp/inapplebag bagcat cat cat

启动pyspark:

$ ./spark/bin/pyspark

使用textFile创建RDD:

>>> txt = sc.textFile("file:///tmp/in", 2)

查看RDD分区与数据:

>>> txt.glom().collect()[[u'apple', u'bag bag'], [u'cat cat cat']]

2. transformation

flatMap

处理RDD的每一行,一对多映射。

代码示例:

>>> txt.flatMap(lambda line: line.split()).collect()[u'apple', u'bag', u'bag', u'cat', u'cat', u'cat']

示意图:

405877-20161215233214183-991773391.png

map

处理RDD的每一行,一对一映射。

代码示例:

>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).collect()[(u'apple', 1), (u'bag', 1), (u'bag', 1), (u'cat', 1), (u'cat', 1), (u'cat', 1)]

示意图:

405877-20161215233237198-1402856491.png

filter

处理RDD的每一行,过滤掉不满足条件的行。

代码示例:

>>> txt.flatMap(lambda line: line.split()).filter(lambda word: word !='bag').collect()[u'apple', u'cat', u'cat', u'cat']

示意图:

405877-20161215233249667-1266028087.png

mapPartitions

逐个处理每一个partition,使用迭代器it访问每个partition的行。

代码示例:

>>> txt.flatMap(lambda line: line.split()).mapPartitions(lambda it: [len(list(it))]).collect()[3, 3]

示意图:

405877-20161215233309479-1547334198.png

mapPartitionsWithIndex

逐个处理每一个partition,使用迭代器it访问每个partition的行,index保存partition的索引,等价于mapPartitionsWithSplit(过期函数)。

代码示例:

>>> txt.flatMap(lambda line: line.split()).mapPartitionsWithIndex(lambda index, it: [index]).collect()[0, 1]

示意图:

405877-20161215233320604-1485558400.png

sample

根据采样因子指定的比例,对数据进行采样,可以选择是否用随机数进行替换,seed用于指定随机数生成器种子。第一个参数表示是否放回抽样,第二个参数表示抽样比例,第三个参数表示随机数seed。

代码示例:

>>> txt.flatMap(lambda line: line.split()).sample(False, 0.5, 5).collect()[u'bag', u'bag', u'cat', u'cat']

示意图:

405877-20161215233335245-240267411.png

union

合并RDD,不去重。

代码示例:

>>> txt.union(txt).collect()[u'apple', u'bag bag', u'cat cat cat', u'apple', u'bag bag', u'cat cat cat']

示意图:

405877-20161215233345573-1659188414.png

distinct

对RDD去重。

代码示例:

>>> txt.flatMap(lambda line: line.split()).distinct().collect()[u'bag', u'apple', u'cat']

示意图:

405877-20161215233357339-1527043575.png

groupByKey

在一个(K,V)对的数据集上调用,返回一个(K,Seq[V])对的数据集。

代码示例:

>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).groupByKey().collect()[(u'bag', 
), (u'apple',
), (u'cat',
)]>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).groupByKey().collect()[0][1].data[1, 1]

示意图:

405877-20161215233409245-515500452.png

reduceByKey

在一个(K,V)对的数据集上调用时,返回一个(K,V)对的数据集,使用指定的reduce函数,将相同key的值聚合到一起。

代码示例:

>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).collect()[(u'bag', 2), (u'apple', 1), (u'cat', 3)]

示意图:

405877-20161215233419183-564791972.png

aggregateByKey

自定义聚合函数,类似groupByKey。在一个(K,V)对的数据集上调用,不过可以返回一个(K,Seq[U])对的数据集。

代码示例(实现groupByKey的功能):

>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).aggregateByKey([], lambda seq, elem: seq + [elem], lambda a, b: a + b).collect()[(u'bag', [1, 1]), (u'apple', [1]), (u'cat', [1, 1, 1])]

sortByKey

在一个(K,V)对的数据集上调用,K必须实现Ordered接口,返回一个按照Key进行排序的(K,V)对数据集。升序或降序由ascending布尔参数决定。

代码示例:

>>> txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).sortByKey().collect()[(u'apple', 1), (u'bag', 2), (u'cat', 3)]

示意图:

405877-20161215233434542-955444502.png

join

在类型为(K,V)和(K,W)类型的数据集上调用时,返回一个相同key对应的所有元素对在一起的(K, (V, W))数据集。

代码示例:

>>> sorted_txt = txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).sortByKey()>>> sorted_txt.join(sorted_txt).collect()[(u'bag', (2, 2)), (u'apple', (1, 1)), (u'cat', (3, 3))]

示意图:

405877-20161215233445479-864837664.png

cogroup

在类型为(K,V)和(K,W)的数据集上调用,返回一个 (K, (Seq[V], Seq[W]))元组的数据集。这个操作也可以称之为groupwith。

代码示例:

>>> sorted_txt = txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).sortByKey()>>> sorted_txt.cogroup(sorted_txt).collect()[(u'bag', (
,
)), (u'apple', (
,
)), (u'cat', (
,
))]>>> sorted_txt.cogroup(sorted_txt).collect()[0][1][0].data[2]

示意图:

405877-20161215233457354-574823858.png

cartesian

笛卡尔积,在类型为 T 和 U 类型的数据集上调用时,返回一个 (T, U)对数据集(两两的元素对)。

代码示例:

>>> sorted_txt = txt.flatMap(lambda line: line.split()).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).sortByKey()>>> sorted_txt.cogroup(sorted_txt).collect()[(u'bag', (
,
)), (u'apple', (
,
)), (u'cat', (
,
))]>>> sorted_txt.cogroup(sorted_txt).collect()[0][1][0].data[2]

示意图:

405877-20161215233509011-1174405091.png

pipe

处理RDD的每一行作为shell命令输入,shell命令结果为输出。

代码示例:

>>> txt.pipe("awk '{print $1}'").collect()[u'apple', u'bag', u'cat']

示意图:

405877-20161215233520308-1081915030.png

coalesce

减少RDD分区数。

代码示例:

>>> txt.coalesce(1).collect()[u'apple', u'bag bag', u'cat cat cat']

示意图:

405877-20161216233704792-1091573312.png

repartition

对RDD重新分区,类似于coalesce。

代码示例:

>>> txt.repartition(1).collect()[u'apple', u'bag bag', u'cat cat cat']

zip

合并两个RDD序列为元组,要求序列长度相等。

代码示例:

>>> txt.zip(txt).collect()[(u'apple', u'apple'), (u'bag bag', u'bag bag'), (u'cat cat cat', u'cat cat cat')]

示意图:

405877-20161215233545198-275024063.png

3. action

reduce

聚集数据集中的所有元素。

代码示例:

>>> txt.reduce(lambda a, b: a + " " + b)u'apple bag bag cat cat cat'

示意图:

405877-20161215233555714-1035268755.png

collect

以数组的形式,返回数据集的所有元素。

代码示例:

>>> txt.collect()[u'apple', u'bag bag', u'cat cat cat']

count

返回数据集的元素的个数。

代码示例:

>>> txt.count()3

first

返回数据集第一个元素。

代码示例:

>>> txt.first()u'apple'

take

返回数据集前n个元素。

代码示例:

>>> txt.take(2)[u'apple', u'bag bag']

takeSample

采样返回数据集前n个元素。第一个参数表示是否放回抽样,第二个参数表示抽样个数,第三个参数表示随机数seed。

代码示例:

>>> txt.takeSample(False, 2, 1)[u'cat cat cat', u'bag bag']

takeOrdered

排序返回前n个元素。

代码示例:

>>> txt.takeOrdered(2)[u'apple', u'bag bag']

saveAsTextFile

将数据集的元素,以textfile的形式,保存到本地文件系统,HDFS或者任何其它hadoop支持的文件系统。

代码示例:

>>> txt.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).reduceByKey(lambda a, b: a + b).saveAsTextFile("file:///tmp/out")

查看输出文件:

$cat /tmp/out/part-00001(u'bag', 2)(u'apple', 1)(u'cat', 3)

saveAsSequenceFile

将数据集的元素,以Hadoop sequencefile的格式,保存到指定的目录下,本地系统,HDFS或者任何其它hadoop支持的文件系统。这个只限于由key-value对组成,并实现了Hadoop的Writable接口,或者隐式的可以转换为Writable的RDD。

countByKey

对(K,V)类型的RDD有效,返回一个(K,Int)对的Map,表示每一个key对应的元素个数。

代码示例:

>>> txt.flatMap(lambda line: line.split(" ")).map(lambda word: (word, 1)).countByKey()defaultdict(
, {u'bag': 2, u'apple': 1, u'cat': 3})

foreach

在数据集的每一个元素上,运行函数func进行更新。这通常用于边缘效果,例如更新一个累加器,或者和外部存储系统进行交互。

代码示例:

>>> def func(line): print line>>> txt.foreach(lambda line: func(line))applebag bagcat cat cat

4. 其他

文中未提及的transformation和action函数可以通过如下命令查询:

>>> dir(txt)['__add__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_computeFractionForSampleSize', '_defaultReducePartitions', '_id', '_jrdd', '_jrdd_deserializer', '_memory_limit', '_pickled', '_reserialize', '_to_java_object_rdd', 'aggregate', 'aggregateByKey', 'cache', 'cartesian', 'checkpoint', 'coalesce', 'cogroup', 'collect', 'collectAsMap', 'combineByKey', 'context', 'count', 'countApprox', 'countApproxDistinct', 'countByKey', 'countByValue', 'ctx', 'distinct', 'filter', 'first', 'flatMap', 'flatMapValues', 'fold', 'foldByKey', 'foreach', 'foreachPartition', 'fullOuterJoin', 'getCheckpointFile', 'getNumPartitions', 'getStorageLevel', 'glom', 'groupBy', 'groupByKey', 'groupWith', 'histogram', 'id', 'intersection', 'isCheckpointed', 'isEmpty', 'is_cached', 'is_checkpointed', 'join', 'keyBy', 'keys', 'leftOuterJoin', 'lookup', 'map', 'mapPartitions', 'mapPartitionsWithIndex', 'mapPartitionsWithSplit', 'mapValues', 'max', 'mean', 'meanApprox', 'min', 'name', 'partitionBy', 'partitioner', 'persist', 'pipe', 'randomSplit', 'reduce', 'reduceByKey', 'reduceByKeyLocally', 'repartition', 'repartitionAndSortWithinPartitions', 'rightOuterJoin', 'sample', 'sampleByKey', 'sampleStdev', 'sampleVariance', 'saveAsHadoopDataset', 'saveAsHadoopFile', 'saveAsNewAPIHadoopDataset', 'saveAsNewAPIHadoopFile', 'saveAsPickleFile', 'saveAsSequenceFile', 'saveAsTextFile', 'setName', 'sortBy', 'sortByKey', 'stats', 'stdev', 'subtract', 'subtractByKey', 'sum', 'sumApprox', 'take', 'takeOrdered', 'takeSample', 'toDF', 'toDebugString', 'toLocalIterator', 'top', 'treeAggregate', 'treeReduce', 'union', 'unpersist', 'values', 'variance', 'zip', 'zipWithIndex', 'zipWithUniqueId']

查询具体函数的使用文档:

>>> help(txt.zipWithIndex)Help on method zipWithIndex in module pyspark.rdd:zipWithIndex(self) method of pyspark.rdd.RDD instance    Zips this RDD with its element indices.        The ordering is first based on the partition index and then the    ordering of items within each partition. So the first item in    the first partition gets index 0, and the last item in the last    partition receives the largest index.        This method needs to trigger a spark job when this RDD contains    more than one partitions.        >>> sc.parallelize(["a", "b", "c", "d"], 3).zipWithIndex().collect()    [('a', 0), ('b', 1), ('c', 2), ('d', 3)](END)

转载地址:http://tlqal.baihongyu.com/

你可能感兴趣的文章
Ubuntu 16.04下搭建kubernetes集群环境
查看>>
9 云计算系列之Cinder的安装与NFS作为cinder后端存储
查看>>
BZOJ 2342: [Shoi2011]双倍回文 [Manacher + set]
查看>>
将内容写入文件
查看>>
微信小程序把玩(二十三)modal组件
查看>>
Zabbix添加自定义监控项(一)
查看>>
ABP入门系列(12)——如何升级Abp并调试源码
查看>>
检查一个类是否能够替换成另一个类,很巧妙
查看>>
Mesos:数据库使用的持久化卷
查看>>
ActiveMQ安全机制设置
查看>>
kibana-1-安装
查看>>
maven insall跳过测试
查看>>
Web攻防系列教程之文件上传攻防解析(转载)
查看>>
c++之——重载、重写、重定义
查看>>
其他分类器
查看>>
HBase 管理,性能调优
查看>>
php 从1加到100
查看>>
centos 解决error: rpmdbNextIterator问题 (转)
查看>>
SQL Server--获取磁盘空间使用情况
查看>>
jquery操作select(增加,删除,清空)
查看>>