1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
|
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Spark Programming Guide - Spark 0.6.0 Documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.1-respond-1.1.0.min.js"></script>
<link rel="stylesheet" href="css/pygments-default.css">
</head>
<body>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p>
<![endif]-->
<!-- This code is taken from http://twitter.github.com/bootstrap/examples/hero.html -->
<div class="navbar navbar-fixed-top" id="topbar">
<div class="navbar-inner">
<div class="container">
<div class="brand"><a href="index.html">
<img src="img/spark-logo-77x50px-hd.png" /></a><span class="version">0.6.0</span>
</div>
<ul class="nav">
<!--TODO(andyk): Add class="active" attribute to li some how.-->
<li><a href="index.html">Overview</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Programming Guides<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="quick-start.html">Quick Start</a></li>
<li><a href="scala-programming-guide.html">Scala</a></li>
<li><a href="java-programming-guide.html">Java</a></li>
</ul>
</li>
<li><a href="api/core/index.html">API (Scaladoc)</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Deploying<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="ec2-scripts.html">Amazon EC2</a></li>
<li><a href="spark-standalone.html">Standalone Mode</a></li>
<li><a href="running-on-mesos.html">Mesos</a></li>
<li><a href="running-on-yarn.html">YARN</a></li>
</ul>
</li>
<li class="dropdown">
<a href="api.html" class="dropdown-toggle" data-toggle="dropdown">More<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="configuration.html">Configuration</a></li>
<li><a href="tuning.html">Tuning Guide</a></li>
<li><a href="bagel-programming-guide.html">Bagel (Pregel on Spark)</a></li>
<li><a href="contributing-to-spark.html">Contributing to Spark</a></li>
</ul>
</li>
</ul>
<!--<p class="navbar-text pull-right"><span class="version-text">v0.6.0</span></p>-->
</div>
</div>
</div>
<div class="container" id="content">
<h1 class="title">Spark Programming Guide</h1>
<ul id="markdown-toc">
<li><a href="#overview">Overview</a></li>
<li><a href="#linking-with-spark">Linking with Spark</a></li>
<li><a href="#initializing-spark">Initializing Spark</a> <ul>
<li><a href="#master-urls">Master URLs</a></li>
<li><a href="#deploying-code-on-a-cluster">Deploying Code on a Cluster</a></li>
</ul>
</li>
<li><a href="#resilient-distributed-datasets-rdds">Resilient Distributed Datasets (RDDs)</a> <ul>
<li><a href="#parallelized-collections">Parallelized Collections</a></li>
<li><a href="#hadoop-datasets">Hadoop Datasets</a></li>
<li><a href="#rdd-operations">RDD Operations</a> <ul>
<li><a href="#transformations">Transformations</a></li>
<li><a href="#actions">Actions</a></li>
</ul>
</li>
<li><a href="#rdd-persistence">RDD Persistence</a> <ul>
<li><a href="#which-storage-level-to-choose">Which Storage Level to Choose?</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#shared-variables">Shared Variables</a> <ul>
<li><a href="#broadcast-variables">Broadcast Variables</a></li>
<li><a href="#accumulators">Accumulators</a></li>
</ul>
</li>
<li><a href="#where-to-go-from-here">Where to Go from Here</a></li>
</ul>
<h1 id="overview">Overview</h1>
<p>At a high level, every Spark application consists of a <em>driver program</em> that runs the user’s <code>main</code> function and executes various <em>parallel operations</em> on a cluster. The main abstraction Spark provides is a <em>resilient distributed dataset</em> (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 <em>persist</em> an RDD in memory, allowing it to be reused efficiently across parallel operations. Finally, RDDs automatically recover from node failures.</p>
<p>A second abstraction in Spark is <em>shared variables</em> 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: <em>broadcast variables</em>, which can be used to cache a value in memory on all nodes, and <em>accumulators</em>, which are variables that are only “added” to, such as counters and sums.</p>
<p>This guide shows each of these features and walks through some samples. It assumes some familiarity with Scala, especially with the syntax for <a href="http://www.scala-lang.org/node/133">closures</a>. Note that you can also run Spark interactively using the <code>spark-shell</code> script. We highly recommend doing that to follow along!</p>
<h1 id="linking-with-spark">Linking with Spark</h1>
<p>To write a Spark application, you will need to add both Spark and its dependencies to your CLASSPATH. If you use sbt or Maven, Spark is available through Maven Central at:</p>
<pre><code>groupId = org.spark_project
artifactId = spark-core_2.9.2
version = 0.6.0
</code></pre>
<p>For other build systems or environments, you can run <code>sbt/sbt assembly</code> to build both Spark and its dependencies into one JAR (<code>core/target/spark-core-assembly-0.6.0.jar</code>), then add this to your CLASSPATH.</p>
<p>In addition, you’ll need to import some Spark classes and implicit conversions. Add the following lines at the top of your program:</p>
<div class="highlight"><pre><code class="scala"><span class="k">import</span> <span class="nn">spark.SparkContext</span>
<span class="k">import</span> <span class="nn">SparkContext._</span>
</code></pre>
</div>
<h1 id="initializing-spark">Initializing Spark</h1>
<p>The first thing a Spark program must do is to create a <code>SparkContext</code> object, which tells Spark how to access a cluster.
This is done through the following constructor:</p>
<div class="highlight"><pre><code class="scala"><span class="k">new</span> <span class="nc">SparkContext</span><span class="o">(</span><span class="n">master</span><span class="o">,</span> <span class="n">jobName</span><span class="o">,</span> <span class="o">[</span><span class="kt">sparkHome</span><span class="o">],</span> <span class="o">[</span><span class="kt">jars</span><span class="o">])</span>
</code></pre>
</div>
<p>The <code>master</code> parameter is a string specifying a <a href="running-on-mesos.html">Mesos</a> cluster to connect to, or a special “local” string to run in local mode, as described below. <code>jobName</code> is a name for your job, which will be shown in the Mesos web UI when running on a cluster. Finally, the last two parameters are needed to deploy your code to a cluster if running in distributed mode, as described later.</p>
<p>In the Spark shell, a special interpreter-aware SparkContext is already created for you, in the variable called <code>sc</code>. Making your own SparkContext will not work. You can set which master the context connects to using the <code>MASTER</code> environment variable. For example, to run on four cores, use</p>
<div class="highlight"><pre><code class="bash"><span class="nv">$ MASTER</span><span class="o">=</span><span class="nb">local</span><span class="o">[</span>4<span class="o">]</span> ./spark-shell
</code></pre>
</div>
<h3 id="master-urls">Master URLs</h3>
<p>The master URL passed to Spark can be in one of the following formats:</p>
<table class="table">
<tr><th>Master URL</th><th>Meaning</th></tr>
<tr><td> local </td><td> Run Spark locally with one worker thread (i.e. no parallelism at all). </td></tr>
<tr><td> local[K] </td><td> Run Spark locally with K worker threads (ideally, set this to the number of cores on your machine).
</td></tr>
<tr><td> spark://HOST:PORT </td><td> Connect to the given <a href="spark-standalone.html">Spark standalone
cluster</a> master. The port must be whichever one your master is configured to use, which is 7077 by default.
</td></tr>
<tr><td> mesos://HOST:PORT </td><td> Connect to the given <a href="running-on-mesos.html">Mesos</a> cluster.
The host parameter is the hostname of the Mesos master. The port must be whichever one the master is configured to use,
which is 5050 by default.
</td></tr>
</table>
<p>For running on YARN, Spark launches an instance of the standalone deploy cluster within YARN; see <a href="running-on-yarn.html">running on YARN</a> for details.</p>
<h3 id="deploying-code-on-a-cluster">Deploying Code on a Cluster</h3>
<p>If you want to run your job on a cluster, you will need to specify the two optional parameters to <code>SparkContext</code> to let it find your code:</p>
<ul>
<li><code>sparkHome</code>: The path at which Spark is installed on your worker machines (it should be the same on all of them).</li>
<li><code>jars</code>: A list of JAR files on the local machine containing your job’s code and any dependencies, which Spark will deploy to all the worker nodes. You’ll need to package your job into a set of JARs using your build system. For example, if you’re using SBT, the <a href="https://github.com/sbt/sbt-assembly">sbt-assembly</a> plugin is a good way to make a single JAR with your code and dependencies.</li>
</ul>
<p>If you run <code>spark-shell</code> on a cluster, any classes you define in the shell will automatically be distributed.</p>
<h1 id="resilient-distributed-datasets-rdds">Resilient Distributed Datasets (RDDs)</h1>
<p>Spark revolves around the concept of a <em>resilient distributed dataset</em> (RDD), which is a fault-tolerant collection of elements that can be operated on in parallel. There are currently two types of RDDs: <em>parallelized collections</em>, which take an existing Scala collection and run functions on it in parallel, and <em>Hadoop datasets</em>, 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.</p>
<h2 id="parallelized-collections">Parallelized Collections</h2>
<p>Parallelized collections are created by calling <code>SparkContext</code>’s <code>parallelize</code> method on an existing Scala collection (a <code>Seq</code> 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:</p>
<div class="highlight"><pre><code class="scala"><span class="n">scala</span><span class="o">></span> <span class="k">val</span> <span class="n">data</span> <span class="k">=</span> <span class="nc">Array</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="o">,</span> <span class="mi">5</span><span class="o">)</span>
<span class="n">data</span><span class="k">:</span> <span class="kt">Array</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Array</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="o">,</span> <span class="mi">5</span><span class="o">)</span>
<span class="n">scala</span><span class="o">></span> <span class="k">val</span> <span class="n">distData</span> <span class="k">=</span> <span class="n">sc</span><span class="o">.</span><span class="n">parallelize</span><span class="o">(</span><span class="n">data</span><span class="o">)</span>
<span class="n">distData</span><span class="k">:</span> <span class="kt">spark.RDD</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span> <span class="n">spark</span><span class="o">.</span><span class="nc">ParallelCollection</span><span class="k">@</span><span class="mi">10</span><span class="n">d13e3e</span>
</code></pre>
</div>
<p>Once created, the distributed dataset (<code>distData</code> here) can be operated on in parallel. For example, we might call <code>distData.reduce(_ + _)</code> to add up the elements of the array. We describe operations on distributed datasets later on.</p>
<p>One important parameter for parallel collections is the number of <em>slices</em> 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 <code>parallelize</code> (e.g. <code>sc.parallelize(data, 10)</code>).</p>
<h2 id="hadoop-datasets">Hadoop Datasets</h2>
<p>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, <a href="http://wiki.apache.org/hadoop/AmazonS3">Amazon S3</a>, Hypertable, HBase, etc). Spark supports text files, <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/SequenceFileInputFormat.html">SequenceFiles</a>, and any other Hadoop InputFormat.</p>
<p>Text file RDDs can be created using <code>SparkContext</code>’s <code>textFile</code> method. This method takes an URI for the file (either a local path on the machine, or a <code>hdfs://</code>, <code>s3n://</code>, <code>kfs://</code>, etc URI). Here is an example invocation:</p>
<div class="highlight"><pre><code class="scala"><span class="n">scala</span><span class="o">></span> <span class="k">val</span> <span class="n">distFile</span> <span class="k">=</span> <span class="n">sc</span><span class="o">.</span><span class="n">textFile</span><span class="o">(</span><span class="s">"data.txt"</span><span class="o">)</span>
<span class="n">distFile</span><span class="k">:</span> <span class="kt">spark.RDD</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="n">spark</span><span class="o">.</span><span class="nc">HadoopRDD</span><span class="k">@</span><span class="mi">1</span><span class="n">d4cee08</span>
</code></pre>
</div>
<p>Once created, <code>distFile</code> can be acted on by dataset operations. For example, we can add up the sizes of all the lines using the <code>map</code> and <code>reduce</code> operations as follows: <code>distFile.map(_.size).reduce(_ + _)</code>.</p>
<p>The <code>textFile</code> 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.</p>
<p>For <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/SequenceFileInputFormat.html">SequenceFiles</a>, use SparkContext’s <code>sequenceFile[K, V]</code> method where <code>K</code> and <code>V</code> are the types of key and values in the file. These should be subclasses of Hadoop’s <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/io/Writable.html">Writable</a> interface, like <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/io/IntWritable.html">IntWritable</a> and <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/io/Text.html">Text</a>. In addition, Spark allows you to specify native types for a few common Writables; for example, <code>sequenceFile[Int, String]</code> will automatically read IntWritables and Texts.</p>
<p>Finally, for other Hadoop InputFormats, you can use the <code>SparkContext.hadoopRDD</code> method, which takes an arbitrary <code>JobConf</code> and input format class, key class and value class. Set these the same way you would for a Hadoop job with your input source.</p>
<h2 id="rdd-operations">RDD Operations</h2>
<p>RDDs support two types of operations: <em>transformations</em>, which create a new dataset from an existing one, and <em>actions</em>, which return a value to the driver program after running a computation on the dataset. For example, <code>map</code> is a transformation that passes each dataset element through a function and returns a new distributed dataset representing the results. On the other hand, <code>reduce</code> 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 <code>reduceByKey</code> that returns a distributed dataset).</p>
<p>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 <code>map</code> will be used in a <code>reduce</code> and return only the result of the <code>reduce</code> to the driver, rather than the larger mapped dataset.</p>
<p>By default, each transformed RDD is recomputed each time you run an action on it. However, you may also <em>persist</em> an RDD in memory using the <code>persist</code> (or <code>cache</code>) 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.</p>
<p>The following tables list the transformations and actions currently supported (see also the <a href="api/core/index.html#spark.RDD">RDD API doc</a> for details):</p>
<h3 id="transformations">Transformations</h3>
<table class="table">
<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>mapPartitions</b>(<i>func</i>) </td>
<td> Similar to map, but runs separately on each partition (block) of the RDD, so <i>func</i> must be of type
Iterator[T] => Iterator[U] when running on an RDD of type T. </td>
</tr>
<tr>
<td> <b>mapPartitionsWithSplit</b>(<i>func</i>) </td>
<td> Similar to mapPartitions, but also provides <i>func</i> with an integer value representing the index of
the split, so <i>func</i> must be of type (Int, Iterator[T]) => Iterator[U] when running on an RDD of type T.
</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>distinct</b>([<i>numTasks</i>])) </td>
<td> Return a new dataset that contains the distinct elements of the source dataset.</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. <br />
<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>sortByKey</b>([<i>ascending</i>], [<i>numTasks</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>
<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>
</table>
<p>A complete list of transformations is available in the <a href="api/core/index.html#spark.RDD">RDD API doc</a>.</p>
<h3 id="actions">Actions</h3>
<table class="table">
<tr><th>Action</th><th>Meaning</th></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>countByKey</b>() </td>
<td> Only available on RDDs of type (K, V). Returns a `Map` of (K, Int) pairs with the count of each key. </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>
<p>A complete list of actions is available in the <a href="api/core/index.html#spark.RDD">RDD API doc</a>.</p>
<h2 id="rdd-persistence">RDD Persistence</h2>
<p>One of the most important capabilities in Spark is <em>persisting</em> (or <em>caching</em>) 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.</p>
<p>You can mark an RDD to be persisted using the <code>persist()</code> or <code>cache()</code> 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.</p>
<p>In addition, each RDD can be stored using a different <em>storage level</em>, 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 <a href="api/core/index.html#spark.storage.StorageLevel"><code>spark.storage.StorageLevel</code></a> object to <code>persist()</code>. The <code>cache()</code> method is a shorthand for using the default storage level, which is <code>StorageLevel.MEMORY_ONLY</code> (store deserialized objects in memory). The complete set of available storage levels is:</p>
<table class="table">
<tr><th style="width:23%">Storage Level</th><th>Meaning</th></tr>
<tr>
<td> MEMORY_ONLY </td>
<td> Store RDD as deserialized Java objects in the JVM. If the 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> MEMORY_AND_DISK </td>
<td> Store RDD as deserialized Java objects in the JVM. If the RDD does not fit in memory, store the
partitions that don't fit on disk, and read them from there when they're needed. </td>
</tr>
<tr>
<td> MEMORY_ONLY_SER </td>
<td> Store RDD as <i>serialized</i> Java objects (one byte array per partition).
This is generally more space-efficient than deserialized objects, especially when using a
<a href="tuning.html">fast serializer</a>, but more CPU-intensive to read.
</td>
</tr>
<tr>
<td> MEMORY_AND_DISK_SER </td>
<td> Similar to MEMORY_ONLY_SER, 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_2, MEMORY_AND_DISK_2, etc. </td>
<td> Same as the levels above, but replicate each partition on two cluster nodes. </td>
</tr>
</table>
<h3 id="which-storage-level-to-choose">Which Storage Level to Choose?</h3>
<p>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:</p>
<ul>
<li>If your RDDs fit comfortably with the default storage level (<code>MEMORY_ONLY</code>), leave them that way. This is the most
CPU-efficient option, allowing operations on the RDDs to run as fast as possible.</li>
<li>If not, try using <code>MEMORY_ONLY_SER</code> and <a href="tuning.html">selecting a fast serialization library</a> to make the objects
much more space-efficient, but still reasonably fast to access.</li>
<li>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.</li>
<li>Use the replicated storage levels if you want fast fault recovery (e.g. if using Spark to serve requests from a web
application). <em>All</em> 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.</li>
</ul>
<h1 id="shared-variables">Shared Variables</h1>
<p>Normally, when a function passed to a Spark operation (such as <code>map</code> or <code>reduce</code>) 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 <em>shared variables</em> for two common usage patterns: broadcast variables and accumulators.</p>
<h2 id="broadcast-variables">Broadcast Variables</h2>
<p>Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks. They can be used, for example, to give every node a copy of a large input dataset in an efficient manner. Spark also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.</p>
<p>Broadcast variables are created from a variable <code>v</code> by calling <code>SparkContext.broadcast(v)</code>. The broadcast variable is a wrapper around <code>v</code>, and its value can be accessed by calling the <code>value</code> method. The interpreter session below shows this:</p>
<div class="highlight"><pre><code class="scala"><span class="n">scala</span><span class="o">></span> <span class="k">val</span> <span class="n">broadcastVar</span> <span class="k">=</span> <span class="n">sc</span><span class="o">.</span><span class="n">broadcast</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">))</span>
<span class="n">broadcastVar</span><span class="k">:</span> <span class="kt">spark.Broadcast</span><span class="o">[</span><span class="kt">Array</span><span class="o">[</span><span class="kt">Int</span><span class="o">]]</span> <span class="k">=</span> <span class="n">spark</span><span class="o">.</span><span class="nc">Broadcast</span><span class="o">(</span><span class="n">b5c40191</span><span class="o">-</span><span class="n">a864</span><span class="o">-</span><span class="mi">4</span><span class="n">c7d</span><span class="o">-</span><span class="n">b9bf</span><span class="o">-</span><span class="n">d87e1a4e787c</span><span class="o">)</span>
<span class="n">scala</span><span class="o">></span> <span class="n">broadcastVar</span><span class="o">.</span><span class="n">value</span>
<span class="n">res0</span><span class="k">:</span> <span class="kt">Array</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Array</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">)</span>
</code></pre>
</div>
<p>After the broadcast variable is created, it should be used instead of the value <code>v</code> in any functions run on the cluster so that <code>v</code> is not shipped to the nodes more than once. In addition, the object <code>v</code> should not be modified after it is broadcast in order to ensure that all nodes get the same value of the broadcast variable (e.g. if the variable is shipped to a new node later).</p>
<h2 id="accumulators">Accumulators</h2>
<p>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 type Int and Double, and programmers can add support for new types.</p>
<p>An accumulator is created from an initial value <code>v</code> by calling <code>SparkContext.accumulator(v)</code>. Tasks running on the cluster can then add to it using the <code>+=</code> operator. However, they cannot read its value. Only the driver program can read the accumulator’s value, using its <code>value</code> method.</p>
<p>The interpreter session below shows an accumulator being used to add up the elements of an array:</p>
<div class="highlight"><pre><code class="scala"><span class="n">scala</span><span class="o">></span> <span class="k">val</span> <span class="n">accum</span> <span class="k">=</span> <span class="n">sc</span><span class="o">.</span><span class="n">accumulator</span><span class="o">(</span><span class="mi">0</span><span class="o">)</span>
<span class="n">accum</span><span class="k">:</span> <span class="kt">spark.Accumulator</span><span class="o">[</span><span class="kt">Int</span><span class="o">]</span> <span class="k">=</span> <span class="mi">0</span>
<span class="n">scala</span><span class="o">></span> <span class="n">sc</span><span class="o">.</span><span class="n">parallelize</span><span class="o">(</span><span class="nc">Array</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="mi">2</span><span class="o">,</span> <span class="mi">3</span><span class="o">,</span> <span class="mi">4</span><span class="o">)).</span><span class="n">foreach</span><span class="o">(</span><span class="n">x</span> <span class="k">=></span> <span class="n">accum</span> <span class="o">+=</span> <span class="n">x</span><span class="o">)</span>
<span class="o">...</span>
<span class="mi">10</span><span class="o">/</span><span class="mi">09</span><span class="o">/</span><span class="mi">29</span> <span class="mi">18</span><span class="k">:</span><span class="err">41</span><span class="kt">:</span><span class="err">08</span> <span class="kt">INFO</span> <span class="kt">SparkContext:</span> <span class="kt">Tasks</span> <span class="kt">finished</span> <span class="kt">in</span> <span class="err">0</span><span class="kt">.</span><span class="err">317106</span> <span class="kt">s</span>
<span class="n">scala</span><span class="o">></span> <span class="n">accum</span><span class="o">.</span><span class="n">value</span>
<span class="n">res2</span><span class="k">:</span> <span class="kt">Int</span> <span class="o">=</span> <span class="mi">10</span>
</code></pre>
</div>
<h1 id="where-to-go-from-here">Where to Go from Here</h1>
<p>You can see some <a href="http://www.spark-project.org/examples.html">example Spark programs</a> on the Spark website.
In addition, Spark includes several sample programs in <code>examples/src/main/scala</code>. 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 <code>run</code> script included in Spark – for example, <code>./run spark.examples.SparkPi</code>. Each example program prints usage help when run without any arguments.</p>
<p>For help on optimizing your program, the <a href="configuration.html">configuration</a> and
<a href="tuning.html">tuning</a> guides provide information on best practices. They are especially important for
making sure that your data is stored in memory in an efficient format.</p>
<!-- Main hero unit for a primary marketing message or call to action -->
<!--<div class="hero-unit">
<h1>Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-large">Learn more »</a></p>
</div>-->
<!-- Example row of columns -->
<!--<div class="row">
<div class="span4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
<div class="span4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
<div class="span4">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
<hr>-->
<!--<footer>
<p></p>
</footer>-->
</div> <!-- /container -->
<script src="js/vendor/jquery-1.8.0.min.js"></script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- A script to fix internal hash links because we have an overlapping top bar.
Based on https://github.com/twitter/bootstrap/issues/193#issuecomment-2281510 -->
<script>
$(function() {
function maybeScrollToHash() {
if (window.location.hash && $(window.location.hash).length) {
var newTop = $(window.location.hash).offset().top - $('#topbar').height() - 5;
$(window).scrollTop(newTop);
}
}
$(window).bind('hashchange', function() {
maybeScrollToHash();
});
// Scroll now too in case we had opened the page on a hash, but wait 1 ms because some browsers
// will try to do *their* initial scroll after running the onReady handler.
setTimeout(function() { maybeScrollToHash(); }, 1)
})
</script>
</body>
</html>
|