天天看点

spark2学习(2) 之RDD编程 RDD编程指南弹性分布式数据集(RDD)

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操作

Transformation Meaning
map(func) Return a new distributed dataset formed by passing each element of the source through a function func.
filter(func) Return a new dataset formed by selecting those elements of the source on which funcreturns true.
flatMap(func) Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).
mapPartitions(func) Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func) Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement, fraction, seed) Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.
union(otherDataset) Return a new dataset that contains the union of the elements in the source dataset and the argument.
intersection(otherDataset) Return a new RDD that contains the intersection of elements in the source dataset and the argument.
distinct([numPartitions])) Return a new dataset that contains the distinct elements of the source dataset.
groupByKey([numPartitions])

When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs. 

Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using 

reduceByKey

 or 

aggregateByKey

 will yield much better performance. 

Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional 

numPartitions

 argument to set a different number of tasks.
reduceByKey(func, [numPartitions]) When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in 

groupByKey

, the number of reduce tasks is configurable through an optional second argument.
aggregateByKey(zeroValue)(seqOp, combOp, [numPartitions]) When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. Allows an aggregated value type that is different than the input value type, while avoiding unnecessary allocations. Like in 

groupByKey

, the number of reduce tasks is configurable through an optional second argument.
sortByKey([ascending], [numPartitions]) When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean 

ascending

 argument.
join(otherDataset, [numPartitions]) When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through 

leftOuterJoin

rightOuterJoin

, and 

fullOuterJoin

.
cogroup(otherDataset, [numPartitions]) When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called 

groupWith

.
cartesian(otherDataset) When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).
pipe(command, [envVars]) Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.
coalesce(numPartitions) Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.
repartition(numPartitions) Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.
repartitionAndSortWithinPartitions(partitioner) Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling 

repartition

 and then sorting within each partition because it can push the sorting down into the shuffle machinery.

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 using

SparkContext.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查看累加效果如下:

spark2学习(2) 之RDD编程 RDD编程指南弹性分布式数据集(RDD)

继续阅读