之前我们把RDD讲解了一下,这篇文章就进行简单的使用
这里例用官方文档进行解读:http://spark.apache.org/docs/latest/rdd-programming-guide.html
在IDEA中创建Spark应用程序
在IDEA中添加了spark以后,我们就可以在spark classes 中添加依赖了:
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
The first thing a Spark program must do is to create a SparkContext object, which tells Spark how to access a cluster. To create a SparkContext you first need to build a SparkConf object that contains information about your application.
这里明确指出了第一件事情就是创建一个SparkContext object,这将告诉Spark如何去访问。而在创立SparkContext之前你需要一个SparkConf来收集信息,因此需要添加:
val conf = new SparkConf().setAppName(appName).setMaster(master)
new SparkContext(conf)
类似于这个样子。别忘了停止,否则是会占用资源的
这里要注意一下,不要进行硬编码,因为代码里的优先级是高于外部传递的
Creat RDDs
There are two ways to create RDDs: parallelizing an existing collection in your driver program, or referencing a dataset in an external storage system, such as a shared filesystem, HDFS, HBase, or any data source offering a Hadoop InputFormat.
根据这一段概述,我们可以知道,创建RDD有两种方法:一种是用集合的方式来创建,另一种是通过外部数据源进行创建,只要是有Hadoop的input format。也就是说,它可以通过外部数据源进行操作,从而更加万金油的进行处理,因此,这也是生产环境上最常使用的方式。
Parallelized Collections
这里利用文档给出的一段代码:
val data = Array(1, 2, 3, 4, 5)
val distData = sc.parallelize(data)
这里使用了sc的parallelize方法来构建了一个RDD,我们可以到parallelize中看一下源码怎么写的
不难看出就是将传入的集合变成RDD。
接下来我们试一下
成功打印
External Datasets
同样文档的代码:
scala> val distFile = sc.textFile("data.txt")
distFile: org.apache.spark.rdd.RDD[String] = data.txt MapPartitionsRDD[10] at textFile at <console>:26
这里使用了sc的textFile读取磁盘数据,看一下源码:
我们也使用一下看看可不可以成功:
成功读取
在文档中有这么一段:
这个说明了需要注意的几点:
- 如果访问的是本地的文件系统,那么它必须在其他工作节点的同一目录下访问的到,要么拷贝到所有节点上去,或者使用同一网络共享的文件系统(类似于HDFS这种)
- Spark读取文件可以是目录,压缩文件,甚至是模糊匹配
- 输入的第二个参数可以控制你文件分区的数量,默认是有分区的,你的分区数一定要大于blocks的数量,虽然这么做可以,但是你每一个task处理量比较大,可能会有些问题
RDD Operations
RDDs support two types of operations: transformations, which create a new dataset from an existing one, and actions, which return a value to the driver program after running a computation on the dataset.
根据这一段概述,我们可以看出来,RDD支持两种操作:一个是transformations,再现有的基础上再创建一个dataset(数据集),另一个就是:actions, 它在dataset进行运算以后返回数值。
简单来说,就是transformations是rdd转一个rdd,是一个惰性操作,并不会立刻执行操作,而actions需要返回一个值,因此会进行计算,产生一个job,这个是可以在SparkUI查看的。
transformations:http://spark.apache.org/docs/latest/rdd-programming-guide.html#transformations
actions:http://spark.apache.org/docs/latest/rdd-programming-guide.html#actions