Spark Programming Model : Resilient Distributed Dataset (RDD)
bogotobogo.com site search:
Core Concept
Thing of a program as a set of transformations on a distributed dataset.
Our program get output from the dataset.
So, what programming model we use?
Resilient Distributed Dataset (RDD):
- Read Only collection of objects spread across a cluster.
- RDDs are built through parallel transformations (map, filter, reduce, etc.)
- Automatically rebuilt on failure using lineage.
- Controllable persistence (Ram, HDFS, etc.)
Picture source: 2015 Typesafe survey.
Operations
- Create - from stable storage(HDFS)
- Transform
- Generate RDD from other RDD (map, filter, groupBy)
- Lazy operations that builds a DAG (Directed Acyclic Graph)
- Once Spark knows our transformations, it starts building an efficient plan.
- Action - returns a result or write to storage (count, collect, reduce, save)
Picture source: Survey Confirms Apache Spark Traction in Big Data Analytics
Demo - Log Mining
As a demo, we'll launch and use Scala shell, load a file from HDFS, and then search for patterns.
Let's fire up Spark-shell:
[cloudera@quickstart MYSPARK]$ cd $SPARK_HOME
[cloudera@quickstart spark]$ ls
bin cloudera conf lib LICENSE NOTICE python RELEASE sbin ui-resources work
[cloudera@quickstart spark]$ ./bin/spark-shell
15/05/03 12:22:37 INFO SecurityManager: Changing view acls to: cloudera
15/05/03 12:22:37 INFO SecurityManager: Changing modify acls to: cloudera
15/05/03 12:22:37 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(cloudera); users with modify permissions: Set(cloudera)
15/05/03 12:22:37 INFO HttpServer: Starting HTTP Server
15/05/03 12:22:37 INFO Utils: Successfully started service 'HTTP class server' on port 60604.
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/___/ .__/\_,_/_/ /_/\_\ version 1.2.0
/_/
Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_67)
Spark context available as sc.
scala>
At this point, we can use CDH UI to check the Spark's master:
Let's copy Spark's log to HDFS:
[cloudera@quickstart ~]$ sudo su hdfs
bash-4.1$ hadoop fs -cp /var/log/system.log /user/hdfs/.
bash-4.1$ hadoop fs -copyFromLocal /var/log/spark/spark-master-quickstart.cloudera.log /user/hdfs/.
Let's get RDD from the log:
scala> val textFile = sc.textFile("hdfs:///user/hdfs/spark-master-quickstart.cloudera.log")
Then, search for lines with "Error" and cache it:
scala> val linesWithError = textFile.filter(line => line.contains("Error"))
linesWithError: org.apache.spark.rdd.RDD[String] = FilteredRDD[4] at filter at :14
scala> linesWithError.cache()
res0: linesWithError.type = FilteredRDD[4] at filter at :14
Now we want to filter the lines that has "spark":
scala> linesWithError.filter(_.contains("spark")).count
...
res2: Long = 3
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.
For example, map is a transformation that passes each dataset element through a function and returns a new RDD representing the results. On the other hand, reduce is an action that aggregates all the elements of the RDD using some function and returns the final result to the driver program (although there is also a parallel reduceByKey that returns a distributed dataset).
All transformations in Spark are lazy, in that they do not compute their results right away. Instead, they just remember the transformations applied to some base dataset (e.g. a file). The transformations are only computed when an action requires a result to be returned to the driver program. This design enables Spark to run more efficiently â for example, we can realize that a dataset created through map will be used in a reduce and return only the result of the reduce to the driver, rather than the larger mapped dataset.
Picture from Understanding Spark Internals
By default, each transformed RDD may be recomputed each time we run an action on it. However, we may also persist an RDD in memory using the persist (or cache) method, in which case Spark will keep the elements around on the cluster for much faster access the next time you query it. There is also support for persisting RDDs on disk, or replicated across multiple nodes.
RDD transformations
The following table lists some of the common transformations supported by Spark. Refer to the
RDD API doc (Scala, Java, python) and pair RDD functions doc (Scala, Java) for details.
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 func returns 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([numTasks])) |
Return a new dataset that contains the distinct elements of the source dataset. |
groupByKey([numTasks]) |
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 numTasks argument to set a different number of tasks.
|
reduceByKey(func, [numTasks]) |
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, [numTasks]) |
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], [numTasks]) |
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, [numTasks]) |
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, [numTasks]) |
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. |
RDD action
The following table lists some of the common actions supported by Spark. Refer to the
RDD API doc (Scala, Java, Python) and pair RDD functions doc (Scala, Java) for details.
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 either 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 variable (see below) or interacting with external storage systems. |
RDD Fault tolerance
RDDs maintain lineage information that can be used to reconstruct lost partitions:
Picture from An Intro to Apache Spark (w Hadoop) for Plain Old Java Geeks.