RDD编程指南
实际上从spark2开始就不推荐使用rdd了,使用dataset操作更加简单高效,但是我们还是简单介绍一下内容吧
弹性分布式数据集(RDD)
Spark围绕弹性分布式数据集(RDD)的概念展开,RDD是可以并行操作的容错的容错集合。创建RDD有两种方法:并行化 驱动程序中的现有集合,或引用外部存储系统中的数据集,例如共享文件系统,HDFS,HBase或提供Hadoop InputFormat的任何数据源。
代码书写
配置maven依赖
groupId = org.apache.spark
artifactId = spark-core_2.11
version = 2.3.1
导入使用的包
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
初始化spark上下文,每个jvm只能有一个上下文
val conf = new SparkConf().setAppName(appName).setMaster(master)
val sc=new SparkContext(conf)
构建测试rdd,测试的时候常常使用这个的构建方式
val data = Array(1, 2, 3, 4, 5)
val distData = sc.parallelize(data)
读取hdfs文件作为rdd
val distFile = sc.textFile("data.txt")
创建后,distFile
可以通过数据集操作执行操作。例如,我们可以使用map
和reduce
操作添加所有行的大小,如下所示:distFile.map(s => s.length).reduce((a, b) => a + b)
。
所有Spark的基于文件的输入方法,包括textFile
支持在目录,压缩文件和通配符上运行。例如,你可以使用textFile("/my/directory")
,textFile("/my/directory/*.txt")
和textFile("/my/directory/*.gz")
。
对于SequenceFiles,使用SparkContext.sequenceFile[K, V]
方法,其中K
和V
是文件中键和值的类型。
RDD操作
RDD支持两种类型的操作:转换(从现有数据集创建新数据集)和action操作(在数据集上运行计算后将值返回到driver程序),Spark中的所有转换都是lazy的,因为它们不会立即计算结果。相反,他们只记得应用于某些基础数据集的转换。仅当action操作需要将结果返回到driver时才会计算转换。这种设计使Spark能够更有效地运行spark
了解闭包
Spark的一个难点是在跨集群执行代码时理解变量和方法的范围和生命周期。修改其范围之外的变量的RDD操作可能经常引起混淆。
var counter = 0
var rdd = sc.parallelize(data)
// Wrong: Don't do this!!
rdd.foreach(x => counter += x)
println("Counter value: " + counter)
这段代码在本地模式下似乎没什么问题,但是在集群上就不能得到满意的答案了,这里就是闭包的问题。
在集群模式下foreach里的代码是在每个work上执行的,而driver上声明的变量这样的传递,程序会将counter序列化发送到work,然后work反序列化到counter等于0,所有这样的累加不会收集到driver上。最后的打印语句counter还是0。这里一定好深刻理解。
如果需要某些全局聚合,请使用累加器(Accumulator
)。
元组的操作
val lines = sc.textFile("data.txt")
val pairs = lines.map(s => (s, 1))
val counts = pairs.reduceByKey((a, b) => a + b)
读取文件,使用map将rdd[String]转换成rdd[(String,Int)]。然后使用reduceByKey操作,这里的a和b是迭代器前一个和后一个的操作。counts.sortByKey()
例如,我们还可以使用按字母顺序对对进行排序,最后 counts.collect()
将它们作为对象数组返回到driver程序。
Transformations操作
Actions操作
Action | Meaning |
---|---|
reduce(func) | Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel. |
collect() | Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data. |
count() | Return the number of elements in the dataset. |
first() | Return the first element of the dataset (similar to take(1)). |
take(n) | Return an array with the first n elements of the dataset. |
takeSample(withReplacement, num, [seed]) | Return an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed. |
takeOrdered(n, [ordering]) | Return the first n elements of the RDD using either their natural order or a custom comparator. |
saveAsTextFile(path) | Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file. |
saveAsSequenceFile(path) (Java and Scala) | Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that implement Hadoop's Writable interface. In Scala, it is also available on types that are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc). |
saveAsObjectFile(path) (Java and Scala) | Write the elements of the dataset in a simple format using Java serialization, which can then be loaded usingSparkContext.objectFile() . |
countByKey() | Only available on RDDs of type (K, V). Returns a hashmap of (K, Int) pairs with the count of each key. |
foreach(func) | Run a function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems. Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details. |
RDD 缓存
至此便可得出cache和persist的区别了:cache只有一个默认的缓存级别MEMORY_ONLY ,而persist可以根据情况设置其它的缓存级别。缓存是LRU的机制自动删除的,我们可以手动删除使用 RDD.unpersist()
共享变量分为广播变量和累加器
广播变量
scala> val broadcastVar = sc.broadcast(Array(1, 2, 3))
broadcastVar: org.apache.spark.broadcast.Broadcast[Array[Int]] = Broadcast(0)
scala> broadcastVar.value
res0: Array[Int] = Array(1, 2, 3)
广播变量是可以修改的,例如删除后重新广播。可以广播比较大的数据,这些数据都缓存在内存中,如果是大表和小表的jion,使用广播小表的形式是比较高效的。
累加器
代码如下
scala> val accum = sc.longAccumulator("My Accumulator")
accum: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 0, name: Some(My Accumulator), value: 0)
scala> sc.parallelize(Array(1, 2, 3, 4)).foreach(x => accum.add(x))
...
10/09/29 18:41:08 INFO SparkContext: Tasks finished in 0.317106 s
scala> accum.value
res2: Long = 10
spark的ui查看累加效果如下: