https://spark.apache.org/docs/latest/rdd-programming-guide.html

什么是RDD

RDD: resilient distributed dataset,分布式弹性数据集。 which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel. 集合里的元素被分区在不同的集群节点上,每个节点使用一个子集进行并行计算。

Spark提供了两个底层抽象:
1,RDD,Spark都是基于此概念
2,用于并行计算的共享变量,有且有两个:广播、累加器

创建RDD的方法

两种方法:手动并行化driver program里面的集合对象、加载外部存储的数据集
1,手动并行

  1. val data = Array(1, 2, 3, 4, 5)
  2. val distData = sc.parallelize(data, 2) // 第二个参数是可选的partition数量

原文提到了一个很关键的信息:

One important parameter for parallel collections is the number of partitions to cut the dataset into. Spark will run one task for each partition of the cluster.

Spark会在集群上每个partition执行一个task(会解答下面遇到的疑问,执行最小单元)。
2,加载外部数据集

  1. val distFile = sc.textFile("data.txt")

这个部分有个问题没有弄明白,原文是这么描述的:

The textFile method also takes an optional second argument for controlling the number of partitions of the file. By default, Spark creates one partition for each block of the file (blocks being 128MB by default in HDFS), but you can also ask for a higher number of partitions by passing a larger value. Note that you cannot have fewer partitions than blocks.

问题:文件的block和Spark创建的partition到是个什么关系?依照上面的理解如下
1,Spark默认为文件的每个block创建一个partition
2,在hdfs上,默认的文件block是128M;一个文件存在一个或多个block
3,可以强制要求更多的partitions,通过传入指定的数量,如sc.textFile("data.txt", 30)
4,不能指定比block数量少的partition数量,如block是5,那么partition数量必须大于等于5
对第4点难以理解,如果partition为10,而block为5这种情况,Spark是怎么处理?
1,partition最本质作用是啥?为了一个partition和一个task进行映射,绑定后派发执行?这样的话,就可以把partition理解成并行计算的最小单元了(理解应该是对的)
2,两个partition可以指向同一个block,但为啥一个partition不能指向2个block了?我现在只能理解是为了传输性能考虑

RDD的操作

分为两类操作:

  • transformation,就是转换、变换
  • action,计算

所有的transformation都是lazy的,只是记录了转换步骤,一定要由action来触发转换的执行。

不要大意closure问题(闭包)

One of the harder things about Spark is understanding the scope and life cycle of variables and methods when executing code across a cluster.

Spark核心解决的问题是并行计算,所谓的closure都是复制的镜像数据(variables and methods),放到分布式集群的节点上的,不会反向同步给镜像源。
所以,所有closure里面的数据更新都只会反应到执行的宿主机上。

昂贵的Shuffle操作

The shuffle is Spark’s mechanism for re-distributing data so that it’s grouped differently across partitions.

reduceByKey这个操作来举例,某个key对应的数据分布在多个或者所有的partition中,这样导致需要很多数据交换。
为了组织shuffle的数据,Spark生产了很多task,引入了MapReduce的概念(下面提到的map、reduce都是指这个意思),我没有很好理解,原文:

To organize data for the shuffle, Spark generates sets of tasks - map tasks to organize the data, and a set of reduce tasks to aggregate it.

1,一个key的数据是如何汇聚到一起?单个partition上的map结果包含了多个key的数据
2,对于一个partition,不需要reduce操作吧
3,新生成的RDD(包含reduceByKey的结果)的partition是如何确定的?