aboutsummaryrefslogtreecommitdiff
path: root/docs/scala-programming-guide.md
diff options
context:
space:
mode:
authorMatei Zaharia <matei@eecs.berkeley.edu>2012-09-25 23:26:56 -0700
committerMatei Zaharia <matei@eecs.berkeley.edu>2012-09-25 23:26:56 -0700
commitf1246cc7c18bd0c155f920f4dc593e88147a94e4 (patch)
tree7dd8f81eab5261f6f2e707b3b668b9a9cc7bdc50 /docs/scala-programming-guide.md
parent051785c7e67b7ba0f2f0b5e078753d3f4f380961 (diff)
downloadspark-f1246cc7c18bd0c155f920f4dc593e88147a94e4.tar.gz
spark-f1246cc7c18bd0c155f920f4dc593e88147a94e4.tar.bz2
spark-f1246cc7c18bd0c155f920f4dc593e88147a94e4.zip
Various enhancements to the programming guide and HTML/CSS
Diffstat (limited to 'docs/scala-programming-guide.md')
-rw-r--r--docs/scala-programming-guide.md203
1 files changed, 171 insertions, 32 deletions
diff --git a/docs/scala-programming-guide.md b/docs/scala-programming-guide.md
index ad06c30dbf..1936c1969d 100644
--- a/docs/scala-programming-guide.md
+++ b/docs/scala-programming-guide.md
@@ -2,15 +2,22 @@
layout: global
title: Spark Programming Guide
---
-At a high level, every Spark application consists of a *driver program* that runs the user's `main` function and executes various *parallel operations* on a cluster. The main abstraction Spark provides is a *distributed dataset*, which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel. Distributed datasets are created by starting with a file in the Hadoop file system (HDFS) or an existing collection in the driver program and possibly transforming it. Users may also ask Spark to *cache* a dataset in memory, allowing it to be reused efficiently across parallel operations. Finally, distributed datasets automatically recover from node failures.
+
+* This will become a table of contents (this text will be scraped).
+{:toc}
+
+
+# Overview
+
+At a high level, every Spark application consists of a *driver program* that runs the user's `main` function and executes various *parallel operations* on a cluster. The main abstraction Spark provides is a *resilient distributed dataset* (RDD), which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel. RDDs are created by starting with a file in the Hadoop file system (or any other Hadoop-supported file system), or an existing Scala collection in the driver program, and transforming it. Users may also ask Spark to *persist* an RDD in memory, allowing it to be reused efficiently across parallel operations. Finally, RDDs automatically recover from node failures.
A second abstraction in Spark is *shared variables* that can be used in parallel operations. By default, when Spark runs a function in parallel as a set of tasks on different nodes, it ships a copy of each variable used in the function to each task. Sometimes, a variable needs to be shared across tasks, or between tasks and the driver program. Spark supports two types of shared variables: *broadcast variables*, which can be used to cache a value in memory on all nodes, and *accumulators*, which are variables that are only "added" to, such as counters and sums.
-This guide shows each of these features and walks through some samples. It assumes some familiarity with Scala, especially with the syntax for [closures](http://www.scala-lang.org/node/133). Note that Spark can be run interactively through the `spark-shell` interpreter. You might want to do that to follow along!
+This guide shows each of these features and walks through some samples. It assumes some familiarity with Scala, especially with the syntax for [closures](http://www.scala-lang.org/node/133). Note that you can also run Spark interactively using the `spark-shell` script. We highly recommend doing that to follow along!
# Linking with Spark
-To write a Spark application, you will need to add both Spark and its dependencies to your CLASSPATH. The easiest way to do this is to run `sbt/sbt assembly` to build both Spark and its dependencies into one JAR (`core/target/spark-core-assembly-0.5.0.jar`), then add this to your CLASSPATH. Alternatively, you can publish Spark to the Maven cache on your machine using `sbt/sbt publish-local`. It will be an artifact called `spark-core` under the organization `org.spark-project`.
+To write a Spark application, you will need to add both Spark and its dependencies to your CLASSPATH. The easiest way to do this is to run `sbt/sbt assembly` to build both Spark and its dependencies into one JAR (`core/target/spark-core-assembly-0.6.0.jar`), then add this to your CLASSPATH. Alternatively, you can publish Spark to the Maven cache on your machine using `sbt/sbt publish-local`. It will be an artifact called `spark-core` under the organization `org.spark-project`.
In addition, you'll need to import some Spark classes and implicit conversions. Add the following lines at the top of your program:
@@ -62,7 +69,7 @@ If you want to run your job on a cluster, you will need to specify the two optio
If some classes will be shared across _all_ your jobs, it's also possible to copy them to the workers manually and set the `SPARK_CLASSPATH` environment variable in `conf/spark-env.sh` to point to them; see [Configuration]({{HOME_PATH}}configuration.html) for details.
-# Distributed Datasets
+# 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.
@@ -101,50 +108,181 @@ For [SequenceFiles](http://hadoop.apache.org/common/docs/current/api/org/apache/
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.
-## Distributed Dataset Operations
+## RDD Operations
-Distributed datasets 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 distributed dataset representing the results. On the other hand, `reduce` is an action that aggregates all the elements of the dataset using some function and returns the final result to the driver program (although there is also a parallel `reduceByKey` that returns a distributed dataset).
+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 distributed dataset representing the results. On the other hand, `reduce` is an action that aggregates all the elements of the dataset 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 <i>lazy</i>, 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.
-One important transformation provided by Spark is *caching*. When you cache a distributed dataset, 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.
+By default, each transformed RDD is recomputed each time you run an action on it. However, you 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 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 supported:
+The following tables list the transformations and actions currently supported (see also the [RDD API doc]({{HOME_PATH}}api/core/index.html#spark.RDD) for details):
### Transformations
<table class="table">
-<tr><th>Transformation</th><th>Meaning</th></tr>
-<tr><td> map(<i>func</i>) </td><td> Return a new distributed dataset formed by passing each element of the source through a function <i>func</i>. </td></tr>
-<tr><td> filter(<i>func</i>) </td><td> Return a new dataset formed by selecting those elements of the source on which <i>func</i> returns true. </td></tr>
-<tr><td> flatMap(<i>func</i>) </td><td> Similar to map, but each input item can be mapped to 0 or more output items (so <i>func</i> should return a Seq rather than a single item). </td></tr>
-<tr><td> sample(<i>withReplacement</i>, <i>frac</i>, <i>seed</i>) </td><td> Sample a fraction <i>frac</i> of the data, with or without replacement, using a given random number seed. </td></tr>
-<tr><td> union(otherDataset) </td><td> Return a new dataset that contains the union of the elements in the source dataset and the argument. </td></tr>
-<tr><td> groupByKey([numTasks]) </td><td> When called on a dataset of (K, V) pairs, returns a dataset of (K, Seq[V]) pairs.
-<strong>Note:</strong> By default, this uses only 8 parallel tasks to do the grouping. You can pass an optional <code>numTasks</code> argument to set a different number of tasks.
-</td></tr>
-<tr><td> reduceByKey(func, [numTasks]) </td><td> 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. Like in <code>groupByKey</code>, the number of reduce tasks is configurable through an optional second argument. </td></tr>
-<tr><td> join(otherDataset, [numTasks]) </td><td> 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. </td></tr>
-<tr><td> groupWith(otherDataset, [numTasks]) </td><td> When called on datasets of type (K, V) and (K, W), returns a dataset of (K, Seq[V], Seq[W]) tuples. This operation is also called CoGroup in other frameworks. </td></tr>
-<tr><td> cartesian(otherDataset) </td><td> When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements). </td></tr>
-<tr><td> sortByKey([ascendingOrder]) </td><td> 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 <code>ascendingOrder</code> argument.</td></tr>
+<tr><th style="width:25%">Transformation</th><th>Meaning</th></tr>
+<tr>
+ <td> <b>map</b>(<i>func</i>) </td>
+ <td> Return a new distributed dataset formed by passing each element of the source through a function <i>func</i>. </td>
+</tr>
+<tr>
+ <td> <b>filter</b>(<i>func</i>) </td>
+ <td> Return a new dataset formed by selecting those elements of the source on which <i>func</i> returns true. </td>
+</tr>
+<tr>
+ <td> <b>flatMap</b>(<i>func</i>) </td>
+ <td> Similar to map, but each input item can be mapped to 0 or more output items (so <i>func</i> should return a Seq rather than a single item). </td></tr>
+<tr>
+ <td> <b>sample</b>(<i>withReplacement</i>, <i>fraction</i>, <i>seed</i>) </td>
+ <td> Sample a fraction <i>fraction</i> of the data, with or without replacement, using a given random number generator seed. </td>
+</tr>
+<tr>
+ <td> <b>union</b>(<i>otherDataset</i>) </td>
+ <td> Return a new dataset that contains the union of the elements in the source dataset and the argument. </td>
+</tr>
+<tr>
+ <td> <b>groupByKey</b>([<i>numTasks</i>]) </td>
+ <td> When called on a dataset of (K, V) pairs, returns a dataset of (K, Seq[V]) pairs.
+<b>Note:</b> By default, this uses only 8 parallel tasks to do the grouping. You can pass an optional <code>numTasks</code> argument to set a different number of tasks.
+</td>
+</tr>
+<tr>
+ <td> <b>reduceByKey</b>(<i>func</i>, [<i>numTasks</i>]) </td>
+ <td> 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. Like in <code>groupByKey</code>, the number of reduce tasks is configurable through an optional second argument. </td>
+</tr>
+<tr>
+ <td> <b>join</b>(<i>otherDataset</i>, [<i>numTasks</i>]) </td>
+ <td> 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. </td>
+</tr>
+<tr>
+ <td> <b>cogroup</b>(<i>otherDataset</i>, [<i>numTasks</i>]) </td>
+ <td> When called on datasets of type (K, V) and (K, W), returns a dataset of (K, Seq[V], Seq[W]) tuples. This operation is also called <code>groupWith</code>. </td>
+</tr>
+<tr>
+ <td> <b>cartesian</b>(<i>otherDataset</i>) </td>
+ <td> When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements). </td>
+</tr>
+<tr>
+ <td> <b>sortByKey</b>([<i>ascending</i>]) </td>
+ <td> 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 <code>ascending</code> argument.</td>
+</tr>
</table>
### Actions
+
<table class="table">
<tr><th>Action</th><th>Meaning</th></tr>
-<tr><td> reduce(<i>func</i>) </td><td> Aggregate the elements of the dataset using a function <i>func</i> (which takes two arguments and returns one). The function should be associative so that it can be computed correctly in parallel. </td></tr>
-<tr><td> collect() </td><td> 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. </td></tr>
-<tr><td> count() </td><td> Return the number of elements in the dataset. </td></tr>
-<tr><td> take(<i>n</i>) </td><td> Return an array with the first <i>n</i> elements of the dataset. Note that this is currently not executed in parallel. Instead, the driver program computes all the elements. </td></tr>
-<tr><td> first() </td><td> Return the first element of the dataset (similar to take(1)). </td></tr>
-<tr><td> saveAsTextFile(path) </td><td> 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. </td></tr>
-<tr><td> saveAsSequenceFile(path) </td><td> 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 only available on RDDs of key-value pairs that either implement Hadoop's Writable interface or are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc). </td></tr>
-<tr><td> foreach(<i>func</i>) </td><td> Run a function <i>func</i> 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. </td></tr>
+<tr>
+ <td> <b>reduce</b>(<i>func</i>) </td>
+ <td> Aggregate the elements of the dataset using a function <i>func</i> (which takes two arguments and returns one). The function should be associative so that it can be computed correctly in parallel. </td>
+</tr>
+<tr>
+ <td> <b>collect</b>() </td>
+ <td> 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. </td>
+</tr>
+<tr>
+ <td> <b>count</b>() </td>
+ <td> Return the number of elements in the dataset. </td>
+</tr>
+<tr>
+ <td> <b>first</b>() </td>
+ <td> Return the first element of the dataset (similar to take(1)). </td>
+</tr>
+<tr>
+ <td> <b>take</b>(<i>n</i>) </td>
+ <td> Return an array with the first <i>n</i> elements of the dataset. Note that this is currently not executed in parallel. Instead, the driver program computes all the elements. </td>
+</tr>
+<tr>
+ <td> <b>takeSample</b>(<i>withReplacement</i>, <i>num</i>, <i>seed</i>) </td>
+ <td> Return an array with a random sample of <i>num</i> elements of the dataset, with or without replacement, using the given random number generator seed. </td>
+</tr>
+<tr>
+ <td> <b>saveAsTextFile</b>(<i>path</i>) </td>
+ <td> 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. </td>
+</tr>
+<tr>
+ <td> <b>saveAsSequenceFile</b>(<i>path</i>) </td>
+ <td> 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 only available on RDDs of key-value pairs that either implement Hadoop's Writable interface or are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc). </td>
+</tr>
+<tr>
+ <td> <b>foreach</b>(<i>func</i>) </td>
+ <td> Run a function <i>func</i> 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. </td>
+</tr>
+</table>
+
+## 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 [`spark.storage.StorageLevel`]({{HOME_PATH}}api/core/index.html#spark.storage.StorageLevel) object to `persist()`. The `cache()` method is a shorthand for using the default storage level, which is `StorageLevel.MEMORY_ONLY_DESER` (store deserialized objects in memory). The complete set of available storage levels is:
+
+<table class="table">
+<tr><th>Storage Level</th><th>Meaning</th></tr>
+<tr>
+ <td> MEMORY_ONLY_DESER </td>
+ <td> Store RDD as deserialized Java objects in the JVM. If the entire RDD does not fit in memory, some partitions will
+ not be cached and will be recomputed on the fly each time they're needed. This is the default level. </td>
+</tr>
+<tr>
+ <td> DISK_AND_MEMORY_DESER </td>
+ <td> Store RDD as deserialized Java objects in the JVM. If the entire RDD does not fit in memory, store the
+ partitions that don't fit on disk, and read them from there the next time they're needed. </td>
+</tr>
+<tr>
+ <td> MEMORY_ONLY </td>
+ <td> Store RDD as <i>serialized</i> Java objects (that is, one large byte array per partition).
+ This is generally more space-efficient than deserialized objects, especially when using a
+ [fast serializer]({{HOME_PATH}}tuning.html), but more CPU-intensive to read.
+ </td>
+</tr>
+<tr>
+ <td> DISK_AND_MEMORY </td>
+ <td> Similar to MEMORY_ONLY, but spill partitions that don't fit in memory to disk instead of recomputing them
+ on the fly each time they're needed. </td>
+</tr>
+<tr>
+ <td> DISK_ONLY </td>
+ <td> Store the RDD partitions only on disk. </td>
+</tr>
+<tr>
+ <td> MEMORY_ONLY_DESER_2 </td>
+ <td> Same as MEMORY_ONLY_DESER, but replicate to two nodes. </td>
+</tr>
+<tr>
+ <td> DISK_AND_MEMORY_DESER_2 </td>
+ <td> Same as DISK_AND_MEMORY_DESER, but replicate to two nodes. </td>
+</tr>
+<tr>
+ <td> MEMORY_ONLY_2 </td>
+ <td> Same as MEMORY_ONLY, but replicate to two nodes. </td>
+</tr>
+<tr>
+ <td> DISK_AND_MEMORY_2 </td>
+ <td> Same as DISK_AND_MEMORY, but replicate to two nodes. </td>
+</tr>
+<tr>
+ <td> DISK_ONLY_2 </td>
+ <td> Same as DISK_ONLY, but replicate to two nodes. </td>
+</tr>
</table>
-### Caching
-Calling `cache()` on an RDD asks that it be stored in memory after the first time it is computed. Different partitions of the dataset will be stored on the different cluster nodes that computed them, making subsequent uses of the dataset faster. The cache is fault-tolerant -- if any partition of an RDD is lost, it will be recomputed using the transformations that originally created it.
+### Which Storage Level to Choose?
+
+As you can see, Spark supports a variety of storage levels that give 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_DESER`), 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` and [selecting a fast serialization library]({{HOME_PATH}}tuning.html) 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 as fast as reading it from disk.
+* Use the replicated storage levels if you want fast fault recovery (e.g. if using Spark to serve requests from a web
+ application). *All* the storage levels provide full fault tolerance by recomputing lost data, but the replicated ones
+ let you continue running tasks on the RDD without waiting to recompute a lost partition.
+
# Shared Variables
@@ -186,6 +324,7 @@ scala> accum.value
res2: Int = 10
{% endhighlight %}
+
# Where to Go from Here
You can see some [example Spark programs](http://www.spark-project.org/examples.html) on the Spark website.