Spark Programming Guide
- Overview
- Linking with Spark
- Initializing Spark
- Resilient Distributed Datasets (RDDs)
- Shared Variables
- Where to Go from Here and walks through some samples. It assumes some familiarity with Scala, especially with the syntax for closures. Note that you can also run Spark interactively using the
bin/spark-shell script. We highly recommend doing that to follow along!
Linking with Spark
Spark 0.9.2 uses Scala 2.10. If you write applications in Scala, you will need to use a compatible Scala version (e.g. 2.10.X) – newer major versions may not work.
To write a Spark application, you need to add a dependency on Spark. If you use SBT or Maven, Spark is available through Maven Central at:
groupId = org.apache.spark artifactId = spark-core_2.10 version = 0.9.2
In addition, if you wish to access an HDFS cluster, you need to add a dependency on
hadoop-client for your version of HDFS:
groupId = org.apache.hadoop artifactId = hadoop-client version = <your-hdfs-version>
For other build systems, you can run
sbt/sbt assembly to pack Spark and its dependencies into one JAR (
assembly/target/scala-2.10/spark-assembly-0.9.2-hadoop*.jar), then add this to your CLASSPATH. Set the HDFS version as described here.
Finally, you need to import some Spark classes and implicit conversions into your program. Add the following lines:
import org.apache.spark.SparkContext import org.apache.spark.SparkContext._
Initializing Spark
The first thing a Spark program must do is to create a
SparkContext object, which tells Spark how to access a cluster.
This is done through the following constructor:
new SparkContext(master, appName, [sparkHome], [jars])
or through
new SparkContext(conf), which takes a SparkConf
object for more advanced configuration.
The
master parameter is a string specifying a Spark or Mesos cluster URL to connect to, or a special “local” string to run in local mode, as described below.
appName is a name for your application, which will be shown in the cluster web UI. Finally, the last two parameters are needed to deploy your code to a cluster if running in distributed mode, as described later.
In the Spark shell, a special interpreter-aware SparkContext is already created for you, in the variable called
sc. Making your own SparkContext will not work. You can set which master the context connects to using the
MASTER environment variable, and you can add JARs to the classpath with the
ADD_JARS variable. For example, to run
bin/spark-shell on four cores, use
$ MASTER=local[4] ./bin/spark-shell
Or, to also add
code.jar to its classpath, use:
$ MASTER=local[4] ADD_JARS=code.jar ./bin/spark-shell
Master URLs
The master URL passed to Spark can be in one of the following formats:
If no master URL is specified, the spark shell defaults to “local”.
For running on YARN, Spark launches an instance of the standalone deploy cluster within YARN; see running on YARN for details.
Deploying Code on a Cluster
If you want to run your application on a cluster, you will need to specify the two optional parameters to
SparkContext to let it find your code:
sparkHome: The path at which Spark is installed on your worker machines (it should be the same on all of them).
jars: A list of JAR files on the local machine containing your application’s code and any dependencies, which Spark will deploy to all the worker nodes. You’ll need to package your application into a set of JARs using your build system. For example, if you’re using SBT, the sbt-assembly plugin is a good way to make a single JAR with your code and dependencies.
If you run
bin/spark-shell on a cluster, you can add JARs to it by specifying the
ADD_JARS environment variable before you launch it. This variable should contain a comma-separated list of JARs. For example,
ADD_JARS=a.jar,b.jar ./bin/spark-shell will launch a shell with
a.jar and
b.jar on its classpath. In addition, any new classes you define in the shell will automatically be distributed.
Resilient Distributed Datasets (RDDs)
Spark revolves around the concept of a resilient distributed dataset (RDD), which is a fault-tolerant collection of elements that can be operated on in parallel. There are currently two types of RDDs: parallelized collections, which take an existing Scala collection and run functions on it in parallel, and Hadoop datasets, which run functions on each record of a file in Hadoop distributed file system or any other storage system supported by Hadoop. Both types of RDDs can be operated on through the same methods.
Parallelized Collections
Parallelized collections are created by calling
SparkContext’s
parallelize method on an existing Scala collection (a
Seq object). The elements of the collection are copied to form a distributed dataset that can be operated on in parallel. For example, here is some interpreter output showing how to create a parallel collection from an array:
scala> val data = Array(1, 2, 3, 4, 5) data: Array[Int] = Array(1, 2, 3, 4, 5) scala> val distData = sc.parallelize(data) distData: spark.RDD[Int] = spark.ParallelCollection@10d13e3e
Once created, the distributed dataset (
distData here) can be operated on in parallel. For example, we might call
distData.reduce(_ + _) to add up the elements of the array. We describe operations on distributed datasets later on.
One important parameter for parallel collections is the number of slices to cut the dataset into. Spark will run one task for each slice of the cluster. Typically you want 2-4 slices for each CPU in your cluster. Normally, Spark tries to set the number of slices automatically based on your cluster. However, you can also set it manually by passing it as a second parameter to
parallelize (e.g.
sc.parallelize(data, 10)).
Hadoop Datasets
Spark can create distributed datasets from any file stored in the Hadoop distributed file system (HDFS) or other storage systems supported by Hadoop (including your local file system, Amazon S3, Hypertable, HBase, etc). Spark supports text files, SequenceFiles, and any other Hadoop InputFormat.
Text file RDDs can be created using
SparkContext’s
textFile method. This method takes an URI for the file (either a local path on the machine, or a
hdfs://,
s3n://,
kfs://, etc URI). Here is an example invocation:
scala> val distFile = sc.textFile("data.txt") distFile: spark.RDD[String] = spark.HadoopRDD@1d4cee08
Once created,
distFile can be acted on by dataset operations. For example, we can add up the sizes of all the lines using the
map and
reduce operations as follows:
distFile.map(_.size).reduce(_ + _).
The
textFile method also takes an optional second argument for controlling the number of slices of the file. By default, Spark creates one slice for each block of the file (blocks being 64MB by default in HDFS), but you can also ask for a higher number of slices by passing a larger value. Note that you cannot have fewer slices than blocks.
For SequenceFiles, use SparkContext’s
sequenceFile[K, V] method where
K and
V are the types of key and values in the file. These should be subclasses of Hadoop’s Writable interface, like IntWritable and Text. In addition, Spark allows you to specify native types for a few common Writables; for example,
sequenceFile[Int, String] will automatically read IntWritables and Texts.
Finally, for other Hadoop InputFormats, you can use the
SparkContext.hadoopRDD method, which takes an arbitrary
JobConf and input format class, key class and value class. Set these the same way you would for a Hadoop job with your input source.
RDD Operations distributed dataset representing the results. On the other hand,
reduce is an action that aggregates all the elements of the dataset – 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.
By default, each transformed RDD datasets on disk, or replicated across the cluster. The next section in this document describes these options.
The following tables list the transformations and actions currently supported (see also the RDD API doc for details):
Transformations
A complete list of transformations is available in the RDD API doc.
Actions
A complete list of actions is available in the RDD API doc.
RDD Persistence
One of the most important capabilities in Spark is persisting (or caching) a dataset in memory across operations. When you persist an RDD, each node stores any slices of it that it computes in memory and reuses them in other actions on that dataset (or datasets derived from it). This allows future actions to be much faster (often by more than 10x). Caching is a key tool for building iterative algorithms with Spark and for interactive use from the interpreter.
You can mark an RDD to be persisted using the
persist() or
cache() methods on it. The first time it is computed in an action, it will be kept in memory on the nodes. The cache is fault-tolerant – if any partition of an RDD is lost, it will automatically be recomputed using the transformations that originally created it.
In addition, each RDD can be stored using a different storage level, allowing you, for example, to persist the dataset on disk, or persist it in memory but as serialized Java objects (to save space), or even replicate it across nodes. These levels are chosen by passing a
org.apache.spark.storage.StorageLevel object to
persist(). The
cache() method is a shorthand for using the default storage level, which is
StorageLevel.MEMORY_ONLY (store deserialized objects in memory). The complete set of available storage levels is:
Which Storage Level to Choose?
Spark’s storage levels are meant to provide different tradeoffs between memory usage and CPU efficiency. We recommend going through the following process to select one:
- If your RDDs fit comfortably with the default storage level (
MEMORY_ONLY), leave them that way. This is the most CPU-efficient option, allowing operations on the RDDs to run as fast as possible.
- If not, try using
MEMORY_ONLY_SERand selecting a fast serialization library to make the objects much more space-efficient, but still reasonably fast to access.
- Don’t spill to disk unless the functions that computed your datasets are expensive, or they filter a large amount of the data. Otherwise, recomputing a partition is about.
If you want to define your own storage level (say, with replication factor of 3 instead of 2), then use the function factor method
apply() of the
StorageLevel singleton object.
Shared Variables
Normally, when a function passed to a Spark operation (such as
map or
reduce) is executed on a remote cluster node, it works on separate copies of all the variables used in the function. These variables are copied to each machine, and no updates to the variables on the remote machine are propagated back to the driver program. Supporting general, read-write shared variables across tasks would be inefficient. However, Spark does provide two limited types of shared variables for two common usage patterns: broadcast variables and accumulators.
Broadcast Variables
SparkContext.broadcast).
Accumulators
Accumulators are variables that are only “added” to through an associative operation and can therefore be efficiently supported in parallel. They can be used to implement counters (as in MapReduce) or sums. Spark natively supports accumulators of numeric value types and standard mutable collections, and programmers can add support for new types.
An accumulator is created from an initial value
v by calling
SparkContext.accumulator(v). Tasks running on the cluster can then add to it using the
+= operator. However, they cannot read its value. Only the driver program can read the accumulator’s value, using its
value method.
The interpreter session below shows an accumulator being used to add up the elements of an array:
scala> val accum = sc.accumulator(0) accum: spark.Accumulator[Int] = 0 scala> sc.parallelize(Array(1, 2, 3, 4)).foreach(x => accum += x) ... 10/09/29 18:41:08 INFO SparkContext: Tasks finished in 0.317106 s scala> accum.value res2: Int = 10
Where to Go from Here
You can see some example Spark programs on the Spark website.
In addition, Spark includes several samples in
examples/src/main/scala. Some of them have both Spark versions and local (non-parallel) versions, allowing you to see what had to be changed to make the program run on a cluster. You can run them using by passing the class name to the
bin/run-example script included in Spark; for example:
./bin/run-example org.apache.spark.examples.SparkPi
Each example program prints usage help when run without any arguments.
For help on optimizing your program, the configuration and tuning guides provide information on best practices. They are especially important for making sure that your data is stored in memory in an efficient format.