Movatterモバイル変換


[0]ホーム

URL:


RDD Programming Guide

Overview

At a high level, every Spark application consists of adriver program that runs the user’smain function and executes variousparallel operations on a cluster. The main abstraction Spark provides is aresilient 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 topersist 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 isshared 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, andaccumulators, which are variables that are only “added” to, such as counters and sums.

This guide shows each of these features in each of Spark’s supported languages. It is easiest to followalong with if you launch Spark’s interactive shell – eitherbin/spark-shell for the Scala shell orbin/pyspark for the Python one.

Linking with Spark

Spark 4.0.1 works with Python 3.9+. It can use the standard CPython interpreter,so C libraries like NumPy can be used. It also works with PyPy 7.3.6+.

Spark applications in Python can either be run with thebin/spark-submit script which includes Spark at runtime, or by including it in your setup.py as:

install_requires=['pyspark==4.0.1']

To run Spark applications in Python without pip installing PySpark, use thebin/spark-submit script located in the Spark directory.This script will load Spark’s Java/Scala libraries and allow you to submit applications to a cluster.You can also usebin/pyspark to launch an interactive Python shell.

If you wish to access HDFS data, you need to use a build of PySpark linkingto your version of HDFS.Prebuilt packages are also available on the Spark homepagefor common HDFS versions.

Finally, you need to import some Spark classes into your program. Add the following line:

frompysparkimportSparkContext,SparkConf

PySpark requires the same minor version of Python in both driver and workers. It uses the default python version in PATH,you can specify which version of Python you want to use byPYSPARK_PYTHON, for example:

$ PYSPARK_PYTHON=python3.8 bin/pyspark$ PYSPARK_PYTHON=/path-to-your-pypy/pypy bin/spark-submit examples/src/main/python/pi.py

Spark 4.0.1 is built and distributed to work with Scala 2.13by default. (Spark can be built to work with other versions of Scala, too.) To writeapplications in Scala, you will need to use a compatible Scala version (e.g. 2.13.X).

To write a Spark application, you need to add a Maven dependency on Spark. Spark is available through Maven Central at:

groupId = org.apache.sparkartifactId = spark-core_2.13version = 4.0.1

In addition, if you wish to access an HDFS cluster, you need to add a dependency onhadoop-client for your version of HDFS.

groupId = org.apache.hadoopartifactId = hadoop-clientversion = <your-hdfs-version>

Finally, you need to import some Spark classes into your program. Add the following lines:

importorg.apache.spark.SparkContextimportorg.apache.spark.SparkConf

(Before Spark 1.3.0, you need to explicitlyimport org.apache.spark.SparkContext._ to enable essential implicit conversions.)

Spark 4.0.1 supportslambda expressionsfor concisely writing functions, otherwise you can use the classes in theorg.apache.spark.api.java.function package.

Note that support for Java 7 was removed in Spark 2.2.0.

To write a Spark application in Java, you need to add a dependency on Spark. Spark is available through Maven Central at:

groupId = org.apache.sparkartifactId = spark-core_2.13version = 4.0.1

In addition, if you wish to access an HDFS cluster, you need to add a dependency onhadoop-client for your version of HDFS.

groupId = org.apache.hadoopartifactId = hadoop-clientversion = <your-hdfs-version>

Finally, you need to import some Spark classes into your program. Add the following lines:

importorg.apache.spark.api.java.JavaSparkContext;importorg.apache.spark.api.java.JavaRDD;importorg.apache.spark.SparkConf;

Initializing Spark

The first thing a Spark program must do is to create aSparkContext object, which tells Sparkhow to access a cluster. To create aSparkContext you first need to build aSparkConf objectthat contains information about your application.

conf=SparkConf().setAppName(appName).setMaster(master)sc=SparkContext(conf=conf)

The first thing a Spark program must do is to create aSparkContext object, which tells Sparkhow to access a cluster. To create aSparkContext you first need to build aSparkConf objectthat contains information about your application.

Only one SparkContext should be active per JVM. You muststop() the active SparkContext before creating a new one.

valconf=newSparkConf().setAppName(appName).setMaster(master)newSparkContext(conf)

The first thing a Spark program must do is to create aJavaSparkContext object, which tells Sparkhow to access a cluster. To create aSparkContext you first need to build aSparkConf objectthat contains information about your application.

SparkConfconf=newSparkConf().setAppName(appName).setMaster(master);JavaSparkContextsc=newJavaSparkContext(conf);

TheappName parameter is a name for your application to show on the cluster UI.master is aSpark or YARN cluster URL,or a special “local” string to run in local mode.In practice, when running on a cluster, you will not want to hardcodemaster in the program,but ratherlaunch the application withspark-submit andreceive it there. However, for local testing and unit tests, you can pass “local” to run Sparkin-process.

Using the Shell

In the PySpark shell, a special interpreter-aware SparkContext is already created for you, in thevariable calledsc. Making your own SparkContext will not work. You can set which master thecontext connects to using the--master argument, and you can add Python .zip, .egg or .py filesto the runtime path by passing a comma-separated list to--py-files. For third-party Python dependencies,seePython Package Management. You can also add dependencies(e.g. Spark Packages) to your shell session by supplying a comma-separated list of Maven coordinatesto the--packages argument. Any additional repositories where dependencies might exist (e.g. Sonatype)can be passed to the--repositories argument. For example, to runbin/pyspark on exactly four cores, use:

$./bin/pyspark--master"local[4]"

Or, to also addcode.py to the search path (in order to later be able toimport code), use:

$./bin/pyspark--master"local[4]"--py-files code.py

For a complete list of options, runpyspark --help. Behind the scenes,pyspark invokes the more generalspark-submit script.

It is also possible to launch the PySpark shell inIPython, theenhanced Python interpreter. PySpark works with IPython 1.0.0 and later. Touse IPython, set thePYSPARK_DRIVER_PYTHON variable toipython when runningbin/pyspark:

$ PYSPARK_DRIVER_PYTHON=ipython ./bin/pyspark

To use the Jupyter notebook (previously known as the IPython notebook),

$ PYSPARK_DRIVER_PYTHON=jupyterPYSPARK_DRIVER_PYTHON_OPTS=notebook ./bin/pyspark

You can customize theipython orjupyter commands by settingPYSPARK_DRIVER_PYTHON_OPTS.

After the Jupyter Notebook server is launched, you can create a new notebook fromthe “Files” tab. Inside the notebook, you can input the command%pylab inline as part ofyour notebook before you start to try Spark from the Jupyter notebook.

In the Spark shell, a special interpreter-aware SparkContext is already created for you, in thevariable calledsc. Making your own SparkContext will not work. You can set which master thecontext connects to using the--master argument, and you can add JARs to the classpathby passing a comma-separated list to the--jars argument. You can also add dependencies(e.g. Spark Packages) to your shell session by supplying a comma-separated list of Maven coordinatesto the--packages argument. Any additional repositories where dependencies might exist (e.g. Sonatype)can be passed to the--repositories argument. For example, to runbin/spark-shell on exactlyfour cores, use:

$./bin/spark-shell--master"local[4]"

Or, to also addcode.jar to its classpath, use:

$./bin/spark-shell--master"local[4]"--jars code.jar

To include a dependency using Maven coordinates:

$./bin/spark-shell--master"local[4]"--packages"org.example:example:0.1"

For a complete list of options, runspark-shell --help. Behind the scenes,spark-shell invokes the more generalspark-submit script.

Resilient Distributed Datasets (RDDs)

Spark revolves around the concept of aresilient distributed dataset (RDD), which is a fault-tolerant collection of elements that can be operated on in parallel. There are two ways to create RDDs:parallelizingan existing collection in your driver program, or referencing a dataset in an external storage system, such as ashared filesystem, HDFS, HBase, or any data source offering a Hadoop InputFormat.

Parallelized Collections

Parallelized collections are created by callingSparkContext’sparallelize method on an existing iterable or collection in your driver program. The elements of the collection are copied to form a distributed dataset that can be operated on in parallel. For example, here is how to create a parallelized collection holding the numbers 1 to 5:

data=[1,2,3,4,5]distData=sc.parallelize(data)

Once created, the distributed dataset (distData) can be operated on in parallel. For example, we can calldistData.reduce(lambda a, b: a + b) to add up the elements of the list.We describe operations on distributed datasets later on.

Parallelized collections are created by callingSparkContext’sparallelize method on an existing collection in your driver program (a ScalaSeq). The elements of the collection are copied to form a distributed dataset that can be operated on in parallel. For example, here is how to create a parallelized collection holding the numbers 1 to 5:

valdata=Array(1,2,3,4,5)valdistData=sc.parallelize(data)

Once created, the distributed dataset (distData) can be operated on in parallel. For example, we might calldistData.reduce((a, b) => a + b) to add up the elements of the array. We describe operations on distributed datasets later on.

Parallelized collections are created by callingJavaSparkContext’sparallelize method on an existingCollection in your driver program. The elements of the collection are copied to form a distributed dataset that can be operated on in parallel. For example, here is how to create a parallelized collection holding the numbers 1 to 5:

List<Integer>data=Arrays.asList(1,2,3,4,5);JavaRDD<Integer>distData=sc.parallelize(data);

Once created, the distributed dataset (distData) can be operated on in parallel. For example, we might calldistData.reduce((a, b) -> a + b) to add up the elements of the list.We describe operations on distributed datasets later on.

One important parameter for parallel collections is the number ofpartitions to cut the dataset into. Spark will run one task for each partition of the cluster. Typically you want 2-4 partitions for each CPU in your cluster. Normally, Spark tries to set the number of partitions automatically based on your cluster. However, you can also set it manually by passing it as a second parameter toparallelize (e.g.sc.parallelize(data, 10)). Note: some places in the code use the term slices (a synonym for partitions) to maintain backward compatibility.

External Datasets

PySpark can create distributed datasets from any storage source supported by Hadoop, including your local file system, HDFS, Cassandra, HBase,Amazon S3, etc. Spark supports text files,SequenceFiles, and any other HadoopInputFormat.

Text file RDDs can be created usingSparkContext’stextFile method. This method takes a URI for the file (either a local path on the machine, or ahdfs://,s3a://, etc URI) and reads it as a collection of lines. Here is an example invocation:

>>>distFile=sc.textFile("data.txt")

Once created,distFile can be acted on by dataset operations. For example, we can add up the sizes of all the lines using themap andreduce operations as follows:distFile.map(lambda s: len(s)).reduce(lambda a, b: a + b).

Some notes on reading files with Spark:

  • If using a path on the local filesystem, the file must also be accessible at the same path on worker nodes. Either copy the file to all workers or use a network-mounted shared file system.

  • All of Spark’s file-based input methods, includingtextFile, support running on directories, compressed files, and wildcards as well. For example, you can usetextFile("/my/directory"),textFile("/my/directory/*.txt"), andtextFile("/my/directory/*.gz").

  • ThetextFile method also takes an optional second argument for controlling the number of partitions of the file. By default, Spark creates one partition for each block of the file (blocks being 128MB by default in HDFS), but you can also ask for a higher number of partitions by passing a larger value. Note that you cannot have fewer partitions than blocks.

Apart from text files, Spark’s Python API also supports several other data formats:

  • SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast withtextFile, which would return one record per line in each file.

  • RDD.saveAsPickleFile andSparkContext.pickleFile support saving an RDD in a simple format consisting of pickled Python objects. Batching is used on pickle serialization, with default batch size 10.

  • SequenceFile and Hadoop Input/Output Formats

Note this feature is currently markedExperimental and is intended for advanced users. It may be replaced in future with read/write support based on Spark SQL, in which case Spark SQL is the preferred approach.

Writable Support

PySpark SequenceFile support loads an RDD of key-value pairs within Java, converts Writables to base Java types, and pickles theresulting Java objects usingpickle. When saving an RDD of key-value pairs to SequenceFile,PySpark does the reverse. It unpickles Python objects into Java objects and then converts them to Writables. The followingWritables are automatically converted:

Writable TypePython Type
Textstr
IntWritableint
FloatWritablefloat
DoubleWritablefloat
BooleanWritablebool
BytesWritablebytearray
NullWritableNone
MapWritabledict

Arrays are not handled out-of-the-box. Users need to specify customArrayWritable subtypes when reading or writing. When writing,users also need to specify custom converters that convert arrays to customArrayWritable subtypes. When reading, the defaultconverter will convert customArrayWritable subtypes to JavaObject[], which then get pickled to Python tuples. To getPythonarray.array for arrays of primitive types, users need to specify custom converters.

Saving and Loading SequenceFiles

Similarly to text files, SequenceFiles can be saved and loaded by specifying the path. The key and valueclasses can be specified, but for standard Writables this is not required.

>>>rdd=sc.parallelize(range(1,4)).map(lambdax:(x,"a"*x))>>>rdd.saveAsSequenceFile("path/to/file")>>>sorted(sc.sequenceFile("path/to/file").collect())[(1,u'a'),(2,u'aa'),(3,u'aaa')]

Saving and Loading Other Hadoop Input/Output Formats

PySpark can also read any Hadoop InputFormat or write any Hadoop OutputFormat, for both ‘new’ and ‘old’ Hadoop MapReduce APIs.If required, a Hadoop configuration can be passed in as a Python dict. Here is an example using theElasticsearch ESInputFormat:

$./bin/pyspark--jars/path/to/elasticsearch-hadoop.jar>>>conf={"es.resource":"index/type"}# assume Elasticsearch is running on localhost defaults>>>rdd=sc.newAPIHadoopRDD("org.elasticsearch.hadoop.mr.EsInputFormat","org.apache.hadoop.io.NullWritable","org.elasticsearch.hadoop.mr.LinkedMapWritable",conf=conf)>>>rdd.first()# the result is a MapWritable that is converted to a Python dict(u'Elasticsearch ID',{u'field1':True,u'field2':u'Some Text',u'field3':12345})

Note that, if the InputFormat simply depends on a Hadoop configuration and/or input path, andthe key and value classes can easily be converted according to the above table,then this approach should work well for such cases.

If you have custom serialized binary data (such as loading data from Cassandra / HBase), then you will first need totransform that data on the Scala/Java side to something which can be handled by pickle’s pickler.AConverter trait is providedfor this. Simply extend this trait and implement your transformation code in theconvertmethod. Remember to ensure that this class, along with any dependencies required to access yourInputFormat, are packaged into your Spark job jar and included on the PySparkclasspath.

See thePython examples andtheConverter examplesfor examples of using Cassandra / HBaseInputFormat andOutputFormat with custom converters.

Spark can create distributed datasets from any storage source supported by Hadoop, including your local file system, HDFS, Cassandra, HBase,Amazon S3, etc. Spark supports text files,SequenceFiles, and any other HadoopInputFormat.

Text file RDDs can be created usingSparkContext’stextFile method. This method takes a URI for the file (either a local path on the machine, or ahdfs://,s3a://, etc URI) and reads it as a collection of lines. Here is an example invocation:

scala>valdistFile=sc.textFile("data.txt")distFile:org.apache.spark.rdd.RDD[String]=data.txtMapPartitionsRDD[10]attextFileat<console>:26

Once created,distFile can be acted on by dataset operations. For example, we can add up the sizes of all the lines using themap andreduce operations as follows:distFile.map(s => s.length).reduce((a, b) => a + b).

Some notes on reading files with Spark:

  • If using a path on the local filesystem, the file must also be accessible at the same path on worker nodes. Either copy the file to all workers or use a network-mounted shared file system.

  • All of Spark’s file-based input methods, includingtextFile, support running on directories, compressed files, and wildcards as well. For example, you can usetextFile("/my/directory"),textFile("/my/directory/*.txt"), andtextFile("/my/directory/*.gz"). When multiple files are read, the order of the partitions depends on the order the files are returned from the filesystem. It may or may not, for example, follow the lexicographic ordering of the files by path. Within a partition, elements are ordered according to their order in the underlying file.

  • ThetextFile method also takes an optional second argument for controlling the number of partitions of the file. By default, Spark creates one partition for each block of the file (blocks being 128MB by default in HDFS), but you can also ask for a higher number of partitions by passing a larger value. Note that you cannot have fewer partitions than blocks.

Apart from text files, Spark’s Scala API also supports several other data formats:

  • SparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast withtextFile, which would return one record per line in each file. Partitioning is determined by data locality which, in some cases, may result in too few partitions. For those cases,wholeTextFiles provides an optional second argument for controlling the minimal number of partitions.

  • ForSequenceFiles, use SparkContext’ssequenceFile[K, V] method whereK andV are the types of key and values in the file. These should be subclasses of Hadoop’sWritable interface, likeIntWritable andText. 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.

  • For other Hadoop InputFormats, you can use theSparkContext.hadoopRDD method, which takes an arbitraryJobConf and input format class, key class and value class. Set these the same way you would for a Hadoop job with your input source. You can also useSparkContext.newAPIHadoopRDD for InputFormats based on the “new” MapReduce API (org.apache.hadoop.mapreduce).

  • RDD.saveAsObjectFile andSparkContext.objectFile support saving an RDD in a simple format consisting of serialized Java objects. While this is not as efficient as specialized formats like Avro, it offers an easy way to save any RDD.

Spark can create distributed datasets from any storage source supported by Hadoop, including your local file system, HDFS, Cassandra, HBase,Amazon S3, etc. Spark supports text files,SequenceFiles, and any other HadoopInputFormat.

Text file RDDs can be created usingSparkContext’stextFile method. This method takes a URI for the file (either a local path on the machine, or ahdfs://,s3a://, etc URI) and reads it as a collection of lines. Here is an example invocation:

JavaRDD<String>distFile=sc.textFile("data.txt");

Once created,distFile can be acted on by dataset operations. For example, we can add up the sizes of all the lines using themap andreduce operations as follows:distFile.map(s -> s.length()).reduce((a, b) -> a + b).

Some notes on reading files with Spark:

  • If using a path on the local filesystem, the file must also be accessible at the same path on worker nodes. Either copy the file to all workers or use a network-mounted shared file system.

  • All of Spark’s file-based input methods, includingtextFile, support running on directories, compressed files, and wildcards as well. For example, you can usetextFile("/my/directory"),textFile("/my/directory/*.txt"), andtextFile("/my/directory/*.gz").

  • ThetextFile method also takes an optional second argument for controlling the number of partitions of the file. By default, Spark creates one partition for each block of the file (blocks being 128MB by default in HDFS), but you can also ask for a higher number of partitions by passing a larger value. Note that you cannot have fewer partitions than blocks.

Apart from text files, Spark’s Java API also supports several other data formats:

  • JavaSparkContext.wholeTextFiles lets you read a directory containing multiple small text files, and returns each of them as (filename, content) pairs. This is in contrast withtextFile, which would return one record per line in each file.

  • ForSequenceFiles, use SparkContext’ssequenceFile[K, V] method whereK andV are the types of key and values in the file. These should be subclasses of Hadoop’sWritable interface, likeIntWritable andText.

  • For other Hadoop InputFormats, you can use theJavaSparkContext.hadoopRDD method, which takes an arbitraryJobConf and input format class, key class and value class. Set these the same way you would for a Hadoop job with your input source. You can also useJavaSparkContext.newAPIHadoopRDD for InputFormats based on the “new” MapReduce API (org.apache.hadoop.mapreduce).

  • JavaRDD.saveAsObjectFile andJavaSparkContext.objectFile support saving an RDD in a simple format consisting of serialized Java objects. While this is not as efficient as specialized formats like Avro, it offers an easy way to save any RDD.

RDD Operations

RDDs support two types of operations:transformations, which create a new dataset from an existing one, andactions, 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 parallelreduceByKey that returns a distributed dataset).

All transformations in Spark arelazy, 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 throughmap will be used in areduce and return only the result of thereduce to the driver, rather than the larger mapped dataset.

By default, each transformed RDD may be recomputed each time you run an action on it. However, you may alsopersist an RDD in memory using thepersist (orcache) 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.

Basics

To illustrate RDD basics, consider the simple program below:

lines=sc.textFile("data.txt")lineLengths=lines.map(lambdas:len(s))totalLength=lineLengths.reduce(lambdaa,b:a+b)

The first line defines a base RDD from an external file. This dataset is not loaded in memory orotherwise acted on:lines is merely a pointer to the file.The second line defineslineLengths as the result of amap transformation. Again,lineLengthsisnot immediately computed, due to laziness.Finally, we runreduce, which is an action. At this point Spark breaks the computation into tasksto run on separate machines, and each machine runs both its part of the map and a local reduction,returning only its answer to the driver program.

If we also wanted to uselineLengths again later, we could add:

lineLengths.persist()

before thereduce, which would causelineLengths to be saved in memory after the first time it is computed.

To illustrate RDD basics, consider the simple program below:

vallines=sc.textFile("data.txt")vallineLengths=lines.map(s=>s.length)valtotalLength=lineLengths.reduce((a,b)=>a+b)

The first line defines a base RDD from an external file. This dataset is not loaded in memory orotherwise acted on:lines is merely a pointer to the file.The second line defineslineLengths as the result of amap transformation. Again,lineLengthsisnot immediately computed, due to laziness.Finally, we runreduce, which is an action. At this point Spark breaks the computation into tasksto run on separate machines, and each machine runs both its part of the map and a local reduction,returning only its answer to the driver program.

If we also wanted to uselineLengths again later, we could add:

lineLengths.persist()

before thereduce, which would causelineLengths to be saved in memory after the first time it is computed.

To illustrate RDD basics, consider the simple program below:

JavaRDD<String>lines=sc.textFile("data.txt");JavaRDD<Integer>lineLengths=lines.map(s->s.length());inttotalLength=lineLengths.reduce((a,b)->a+b);

The first line defines a base RDD from an external file. This dataset is not loaded in memory orotherwise acted on:lines is merely a pointer to the file.The second line defineslineLengths as the result of amap transformation. Again,lineLengthsisnot immediately computed, due to laziness.Finally, we runreduce, which is an action. At this point Spark breaks the computation into tasksto run on separate machines, and each machine runs both its part of the map and a local reduction,returning only its answer to the driver program.

If we also wanted to uselineLengths again later, we could add:

lineLengths.persist(StorageLevel.MEMORY_ONLY());

before thereduce, which would causelineLengths to be saved in memory after the first time it is computed.

Passing Functions to Spark

Spark’s API relies heavily on passing functions in the driver program to run on the cluster.There are three recommended ways to do this:

  • Lambda expressions,for simple functions that can be written as an expression. (Lambdas do not support multi-statementfunctions or statements that do not return a value.)
  • Localdefs inside the function calling into Spark, for longer code.
  • Top-level functions in a module.

For example, to pass a longer function than can be supported using alambda, considerthe code below:

"""MyScript.py"""if__name__=="__main__":defmyFunc(s):words=s.split("")returnlen(words)sc=SparkContext(...)sc.textFile("file.txt").map(myFunc)

Note that while it is also possible to pass a reference to a method in a class instance (as opposed toa singleton object), this requires sending the object that contains that class along with the method.For example, consider:

classMyClass(object):deffunc(self,s):returnsdefdoStuff(self,rdd):returnrdd.map(self.func)

Here, if we create anew MyClass and calldoStuff on it, themap inside there references thefunc methodof thatMyClass instance, so the whole object needs to be sent to the cluster.

In a similar way, accessing fields of the outer object will reference the whole object:

classMyClass(object):def__init__(self):self.field="Hello"defdoStuff(self,rdd):returnrdd.map(lambdas:self.field+s)

To avoid this issue, the simplest way is to copyfield into a local variable insteadof accessing it externally:

defdoStuff(self,rdd):field=self.fieldreturnrdd.map(lambdas:field+s)

Spark’s API relies heavily on passing functions in the driver program to run on the cluster.There are two recommended ways to do this:

  • Anonymous function syntax,which can be used for short pieces of code.
  • Static methods in a global singleton object. For example, you can defineobject MyFunctions and thenpassMyFunctions.func1, as follows:
objectMyFunctions{deffunc1(s:String):String={...}}myRdd.map(MyFunctions.func1)

Note that while it is also possible to pass a reference to a method in a class instance (as opposed toa singleton object), this requires sending the object that contains that class along with the method.For example, consider:

classMyClass{deffunc1(s:String):String={...}defdoStuff(rdd:RDD[String]):RDD[String]={rdd.map(func1)}}

Here, if we create a newMyClass instance and calldoStuff on it, themap inside there references thefunc1 methodof thatMyClass instance, so the whole object needs to be sent to the cluster. It issimilar to writingrdd.map(x => this.func1(x)).

In a similar way, accessing fields of the outer object will reference the whole object:

classMyClass{valfield="Hello"defdoStuff(rdd:RDD[String]):RDD[String]={rdd.map(x=>field+x)}}

is equivalent to writingrdd.map(x => this.field + x), which references all ofthis. To avoid thisissue, the simplest way is to copyfield into a local variable instead of accessing it externally:

defdoStuff(rdd:RDD[String]):RDD[String]={valfield_=this.fieldrdd.map(x=>field_+x)}

Spark’s API relies heavily on passing functions in the driver program to run on the cluster.In Java, functions are represented by classes implementing the interfaces in theorg.apache.spark.api.java.function package.There are two ways to create such functions:

  • Implement the Function interfaces in your own class, either as an anonymous inner class or a named one,and pass an instance of it to Spark.
  • Uselambda expressionsto concisely define an implementation.

While much of this guide uses lambda syntax for conciseness, it is easy to use all the same APIsin long-form. For example, we could have written our code above as follows:

JavaRDD<String>lines=sc.textFile("data.txt");JavaRDD<Integer>lineLengths=lines.map(newFunction<String,Integer>(){publicIntegercall(Strings){returns.length();}});inttotalLength=lineLengths.reduce(newFunction2<Integer,Integer,Integer>(){publicIntegercall(Integera,Integerb){returna+b;}});

Or, if writing the functions inline is unwieldy:

classGetLengthimplementsFunction<String,Integer>{publicIntegercall(Strings){returns.length();}}classSumimplementsFunction2<Integer,Integer,Integer>{publicIntegercall(Integera,Integerb){returna+b;}}JavaRDD<String>lines=sc.textFile("data.txt");JavaRDD<Integer>lineLengths=lines.map(newGetLength());inttotalLength=lineLengths.reduce(newSum());

Note that anonymous inner classes in Java can also access variables in the enclosing scope as longas they are markedfinal. Spark will ship copies of these variables to each worker node as it doesfor other languages.

Understanding closures

One of the harder things about Spark is understanding the scope and life cycle of variables and methods when executing code across a cluster. RDD operations that modify variables outside of their scope can be a frequent source of confusion. In the example below we’ll look at code that usesforeach() to increment a counter, but similar issues can occur for other operations as well.

Example

Consider the naive RDD element sum below, which may behave differently depending on whether execution is happening within the same JVM. A common example of this is when running Spark inlocal mode (--master = "local[n]") versus deploying a Spark application to a cluster (e.g. via spark-submit to YARN):

counter=0rdd=sc.parallelize(data)# Wrong: Don't do this!!defincrement_counter(x):globalcountercounter+=xrdd.foreach(increment_counter)print("Counter value:",counter)
varcounter=0varrdd=sc.parallelize(data)// Wrong: Don't do this!!rdd.foreach(x=>counter+=x)println("Counter value: "+counter)
intcounter=0;JavaRDD<Integer>rdd=sc.parallelize(data);// Wrong: Don't do this!!rdd.foreach(x->counter+=x);println("Counter value: "+counter);

Local vs. cluster modes

The behavior of the above code is undefined, and may not work as intended. To execute jobs, Spark breaks up the processing of RDD operations into tasks, each of which is executed by an executor. Prior to execution, Spark computes the task’sclosure. The closure is those variables and methods which must be visible for the executor to perform its computations on the RDD (in this caseforeach()). This closure is serialized and sent to each executor.

The variables within the closure sent to each executor are now copies and thus, whencounter is referenced within theforeach function, it’s no longer thecounter on the driver node. There is still acounter in the memory of the driver node but this is no longer visible to the executors! The executors only see the copy from the serialized closure. Thus, the final value ofcounter will still be zero since all operations oncounter were referencing the value within the serialized closure.

In local mode, in some circumstances, theforeach function will actually execute within the same JVM as the driver and will reference the same originalcounter, and may actually update it.

To ensure well-defined behavior in these sorts of scenarios one should use anAccumulator. Accumulators in Spark are used specifically to provide a mechanism for safely updating a variable when execution is split up across worker nodes in a cluster. The Accumulators section of this guide discusses these in more detail.

In general, closures - constructs like loops or locally defined methods, should not be used to mutate some global state. Spark does not define or guarantee the behavior of mutations to objects referenced from outside of closures. Some code that does this may work in local mode, but that’s just by accident and such code will not behave as expected in distributed mode. Use an Accumulator instead if some global aggregation is needed.

Printing elements of an RDD

Another common idiom is attempting to print out the elements of an RDD usingrdd.foreach(println) orrdd.map(println). On a single machine, this will generate the expected output and print all the RDD’s elements. However, incluster mode, the output tostdout being called by the executors is now writing to the executor’sstdout instead, not the one on the driver, sostdout on the driver won’t show these! To print all elements on the driver, one can use thecollect() method to first bring the RDD to the driver node thus:rdd.collect().foreach(println). This can cause the driver to run out of memory, though, becausecollect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use thetake():rdd.take(100).foreach(println).

Working with Key-Value Pairs

While most Spark operations work on RDDs containing any type of objects, a few special operations areonly available on RDDs of key-value pairs.The most common ones are distributed “shuffle” operations, such as grouping or aggregating the elementsby a key.

In Python, these operations work on RDDs containing built-in Python tuples such as(1, 2).Simply create such tuples and then call your desired operation.

For example, the following code uses thereduceByKey operation on key-value pairs to count howmany times each line of text occurs in a file:

lines=sc.textFile("data.txt")pairs=lines.map(lambdas:(s,1))counts=pairs.reduceByKey(lambdaa,b:a+b)

We could also usecounts.sortByKey(), for example, to sort the pairs alphabetically, and finallycounts.collect() to bring them back to the driver program as a list of objects.

While most Spark operations work on RDDs containing any type of objects, a few special operations areonly available on RDDs of key-value pairs.The most common ones are distributed “shuffle” operations, such as grouping or aggregating the elementsby a key.

In Scala, these operations are automatically available on RDDs containingTuple2 objects(the built-in tuples in the language, created by simply writing(a, b)). The key-value pair operations are available in thePairRDDFunctions class,which automatically wraps around an RDD of tuples.

For example, the following code uses thereduceByKey operation on key-value pairs to count howmany times each line of text occurs in a file:

vallines=sc.textFile("data.txt")valpairs=lines.map(s=>(s,1))valcounts=pairs.reduceByKey((a,b)=>a+b)

We could also usecounts.sortByKey(), for example, to sort the pairs alphabetically, and finallycounts.collect() to bring them back to the driver program as an array of objects.

Note: when using custom objects as the key in key-value pair operations, you must be sure that acustomequals() method is accompanied with a matchinghashCode() method. For full details, seethe contract outlined in theObject.hashCode()documentation.

While most Spark operations work on RDDs containing any type of objects, a few special operations areonly available on RDDs of key-value pairs.The most common ones are distributed “shuffle” operations, such as grouping or aggregating the elementsby a key.

In Java, key-value pairs are represented using thescala.Tuple2 classfrom the Scala standard library. You can simply callnew Tuple2(a, b) to create a tuple, and accessits fields later withtuple._1() andtuple._2().

RDDs of key-value pairs are represented by theJavaPairRDD class. You can constructJavaPairRDDs from JavaRDDs using special versions of themap operations, likemapToPair andflatMapToPair. The JavaPairRDD will have both standard RDD functions and specialkey-value ones.

For example, the following code uses thereduceByKey operation on key-value pairs to count howmany times each line of text occurs in a file:

JavaRDD<String>lines=sc.textFile("data.txt");JavaPairRDD<String,Integer>pairs=lines.mapToPair(s->newTuple2(s,1));JavaPairRDD<String,Integer>counts=pairs.reduceByKey((a,b)->a+b);

We could also usecounts.sortByKey(), for example, to sort the pairs alphabetically, and finallycounts.collect() to bring them back to the driver program as an array of objects.

Note: when using custom objects as the key in key-value pair operations, you must be sure that acustomequals() method is accompanied with a matchinghashCode() method. For full details, seethe contract outlined in theObject.hashCode()documentation.

Transformations

The following table lists some of the common transformations supported by Spark. Refer to theRDD API doc(Python,Scala,Java,R)and pair RDD functions doc(Scala,Java)for details.

TransformationMeaning
map(func) Return a new distributed dataset formed by passing each element of the source through a functionfunc.
filter(func) Return a new dataset formed by selecting those elements of the source on whichfunc returns true.
flatMap(func) Similar to map, but each input item can be mapped to 0 or more output items (sofunc should return a Seq rather than a single item).
mapPartitions(func) Similar to map, but runs separately on each partition (block) of the RDD, sofunc must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func) Similar to mapPartitions, but also providesfunc with an integer value representing the index of the partition, sofunc must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
sample(withReplacement,fraction,seed) Sample a fractionfraction 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, usingreduceByKey oraggregateByKey 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 optionalnumPartitions 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 functionfunc, which must be of type (V,V) => V. Like ingroupByKey, 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 ingroupByKey, 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 booleanascending 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 throughleftOuterJoin,rightOuterJoin, andfullOuterJoin.
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 calledgroupWith.
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 callingrepartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.

Actions

The following table lists some of the common actions supported by Spark. Refer to theRDD API doc(Python,Scala,Java,R)

and pair RDD functions doc(Scala,Java)for details.

ActionMeaning
reduce(func) Aggregate the elements of the dataset using a functionfunc (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 firstn elements of the dataset.
takeSample(withReplacement,num, [seed]) Return an array with a random sample ofnum elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.
takeOrdered(n,[ordering]) Return the firstn 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 usingSparkContext.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 functionfunc on each element of the dataset. This is usually done for side effects such as updating anAccumulator or interacting with external storage systems.
Note: modifying variables other than Accumulators outside of theforeach() may result in undefined behavior. SeeUnderstanding closures for more details.

The Spark RDD API also exposes asynchronous versions of some actions, likeforeachAsync forforeach, which immediately return aFutureAction to the caller instead of blocking on completion of the action. This can be used to manage or wait for the asynchronous execution of the action.

Shuffle operations

Certain operations within Spark trigger an event known as the shuffle. The shuffle is Spark’smechanism for re-distributing data so that it’s grouped differently across partitions. This typicallyinvolves copying data across executors and machines, making the shuffle a complex andcostly operation.

Background

To understand what happens during the shuffle, we can consider the example of thereduceByKey operation. ThereduceByKey operation generates a new RDD where allvalues for a single key are combined into a tuple - the key and the result of executing a reducefunction against all values associated with that key. The challenge is that not all values for asingle key necessarily reside on the same partition, or even the same machine, but they must beco-located to compute the result.

In Spark, data is generally not distributed across partitions to be in the necessary place for aspecific operation. During computations, a single task will operate on a single partition - thus, toorganize all the data for a singlereduceByKey reduce task to execute, Spark needs to perform anall-to-all operation. It must read from all partitions to find all the values for all keys,and then bring together values across partitions to compute the final result for each key -this is called theshuffle.

Although the set of elements in each partition of newly shuffled data will be deterministic, and sois the ordering of partitions themselves, the ordering of these elements is not. If one desires predictablyordered data following shuffle then it’s possible to use:

Operations which can cause a shuffle includerepartition operations likerepartition andcoalesce,‘ByKey operations(except for counting) likegroupByKey andreduceByKey, andjoin operations likecogroup andjoin.

Performance Impact

TheShuffle is an expensive operation since it involves disk I/O, data serialization, andnetwork I/O. To organize data for the shuffle, Spark generates sets of tasks -map tasks toorganize the data, and a set ofreduce tasks to aggregate it. This nomenclature comes fromMapReduce and does not directly relate to Spark’smap andreduce operations.

Internally, results from individual map tasks are kept in memory until they can’t fit. Then, theseare sorted based on the target partition and written to a single file. On the reduce side, tasksread the relevant sorted blocks.

Certain shuffle operations can consume significant amounts of heap memory since they employin-memory data structures to organize records before or after transferring them. Specifically,reduceByKey andaggregateByKey create these structures on the map side, and'ByKey operationsgenerate these on the reduce side. When data does not fit in memory Spark will spill these tablesto disk, incurring the additional overhead of disk I/O and increased garbage collection.

Shuffle also generates a large number of intermediate files on disk. As of Spark 1.3, these filesare preserved until the corresponding RDDs are no longer used and are garbage collected.This is done so the shuffle files don’t need to be re-created if the lineage is re-computed.Garbage collection may happen only after a long period of time, if the application retains referencesto these RDDs or if GC does not kick in frequently. This means that long-running Spark jobs mayconsume a large amount of disk space. The temporary storage directory is specified by thespark.local.dir configuration parameter when configuring the Spark context.

Shuffle behavior can be tuned by adjusting a variety of configuration parameters. See the‘Shuffle Behavior’ section within theSpark Configuration Guide.

RDD Persistence

One of the most important capabilities in Spark ispersisting (orcaching) a dataset in memoryacross operations. When you persist an RDD, each node stores any partitions of it that it computes inmemory and reuses them in other actions on that dataset (or datasets derived from it). This allowsfuture actions to be much faster (often by more than 10x). Caching is a key tool foriterative algorithms and fast interactive use.

You can mark an RDD to be persisted using thepersist() orcache() methods on it. The first timeit is computed in an action, it will be kept in memory on the nodes. Spark’s cache is fault-tolerant –if any partition of an RDD is lost, it will automatically be recomputed using the transformationsthat originally created it.

In addition, each persisted RDD can be stored using a differentstorage level, allowing you, for example,to persist the dataset on disk, persist it in memory but as serialized Java objects (to save space),replicate it across nodes.These levels are set by passing aStorageLevel object (Python,Scala,Java)topersist(). Thecache() method is a shorthand for using the default storage level,which isStorageLevel.MEMORY_ONLY (store deserialized objects in memory). The full set ofstorage levels is:

Storage LevelMeaning
MEMORY_ONLY 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.
MEMORY_AND_DISK 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.
MEMORY_ONLY_SER
(Java and Scala)
Store RDD asserialized Java objects (one byte array per partition). This is generally more space-efficient than deserialized objects, especially when using afast serializer, but more CPU-intensive to read.
MEMORY_AND_DISK_SER
(Java and Scala)
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.
DISK_ONLY Store the RDD partitions only on disk.
MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc. Same as the levels above, but replicate each partition on two cluster nodes.
OFF_HEAP (experimental) Similar to MEMORY_ONLY_SER, but store the data inoff-heap memory. This requires off-heap memory to be enabled.

Note:In Python, stored objects will always be serialized with thePickle library,so it does not matter whether you choose a serialized level. The available storage levels in Python includeMEMORY_ONLY,MEMORY_ONLY_2,MEMORY_AND_DISK,MEMORY_AND_DISK_2,DISK_ONLY,DISK_ONLY_2, andDISK_ONLY_3.

Spark also automatically persists some intermediate data in shuffle operations (e.g.reduceByKey), even without users callingpersist. This is done to avoid recomputing the entire input if a node fails during the shuffle. We still recommend users callpersist on the resulting RDD if they plan to reuse it.

Which Storage Level to Choose?

Spark’s storage levels are meant to provide different trade-offs between memory usage and CPUefficiency. We recommend going through the following process to select one:

Removing Data

Spark automatically monitors cache usage on each node and drops out old data partitions in aleast-recently-used (LRU) fashion. If you would like to manually remove an RDD instead of waiting forit to fall out of the cache, use theRDD.unpersist() method. Note that this method does notblock by default. To block until resources are freed, specifyblocking=true when calling this method.

Shared Variables

Normally, when a function passed to a Spark operation (such asmap orreduce) is executed on aremote cluster node, it works on separate copies of all the variables used in the function. Thesevariables are copied to each machine, and no updates to the variables on the remote machine arepropagated back to the driver program. Supporting general, read-write shared variables across taskswould be inefficient. However, Spark does provide two limited types ofshared variables for twocommon usage patterns: broadcast variables and accumulators.

Broadcast Variables

Broadcast variables allow the programmer to keep a read-only variable cached on each machine ratherthan shipping a copy of it with tasks. They can be used, for example, to give every node a copy of alarge input dataset in an efficient manner. Spark also attempts to distribute broadcast variablesusing efficient broadcast algorithms to reduce communication cost.

Spark actions are executed through a set of stages, separated by distributed “shuffle” operations.Spark automatically broadcasts the common data needed by tasks within each stage. The databroadcasted this way is cached in serialized form and deserialized before running each task. Thismeans that explicitly creating broadcast variables is only useful when tasks across multiple stagesneed the same data or when caching the data in deserialized form is important.

Broadcast variables are created from a variablev by callingSparkContext.broadcast(v). Thebroadcast variable is a wrapper aroundv, and its value can be accessed by calling thevaluemethod. The code below shows this:

>>>broadcastVar=sc.broadcast([1,2,3])<pyspark.core.broadcast.Broadcastobjectat0x102789f10>>>>broadcastVar.value[1,2,3]
scala>valbroadcastVar=sc.broadcast(Array(1,2,3))broadcastVar:org.apache.spark.broadcast.Broadcast[Array[Int]]=Broadcast(0)scala>broadcastVar.valueres0:Array[Int]=Array(1,2,3)
Broadcast<int[]>broadcastVar=sc.broadcast(newint[]{1,2,3});broadcastVar.value();// returns [1, 2, 3]

After the broadcast variable is created, it should be used instead of the valuev in any functionsrun on the cluster so thatv is not shipped to the nodes more than once. In addition, the objectv should not be modified after it is broadcast in order to ensure that all nodes get the samevalue of the broadcast variable (e.g. if the variable is shipped to a new node later).

To release the resources that the broadcast variable copied onto executors, call.unpersist().If the broadcast is used again afterwards, it will be re-broadcast. To permanently release allresources used by the broadcast variable, call.destroy(). The broadcast variable can’t be usedafter that. Note that these methods do not block by default. To block until resources are freed,specifyblocking=true when calling them.

Accumulators

Accumulators are variables that are only “added” to through an associative and commutative operation and cantherefore be efficiently supported in parallel. They can be used to implement counters (as inMapReduce) or sums. Spark natively supports accumulators of numeric types, and programmerscan add support for new types.

As a user, you can create named or unnamed accumulators. As seen in the image below, a named accumulator (in this instancecounter) will display in the web UI for the stage that modifies that accumulator. Spark displays the value for each accumulator modified by a task in the “Tasks” table.

Accumulators in the Spark UI

Tracking accumulators in the UI can be useful for understanding the progress ofrunning stages (NOTE: this is not yet supported in Python).

An accumulator is created from an initial valuev by callingSparkContext.accumulator(v). Tasksrunning on a cluster can then add to it using theadd method or the+= operator. However, they cannot read its value.Only the driver program can read the accumulator’s value, using itsvalue method.

The code below shows an accumulator being used to add up the elements of an array:

>>>accum=sc.accumulator(0)>>>accumAccumulator<id=0,value=0>>>>sc.parallelize([1,2,3,4]).foreach(lambdax:accum.add(x))...10/09/2918:41:08INFOSparkContext:Tasksfinishedin0.317106s>>>accum.value10

While this code used the built-in support for accumulators of type Int, programmers can alsocreate their own types by subclassingAccumulatorParam.The AccumulatorParam interface has two methods:zero for providing a “zero value” for your datatype, andaddInPlace for adding two values together. For example, supposing we had aVector classrepresenting mathematical vectors, we could write:

classVectorAccumulatorParam(AccumulatorParam):defzero(self,initialValue):returnVector.zeros(initialValue.size)defaddInPlace(self,v1,v2):v1+=v2returnv1# Then, create an Accumulator of this type:vecAccum=sc.accumulator(Vector(...),VectorAccumulatorParam())

A numeric accumulator can be created by callingSparkContext.longAccumulator() orSparkContext.doubleAccumulator()to accumulate values of type Long or Double, respectively. Tasks running on a cluster can then add to it usingtheadd method. However, they cannot read its value. Only the driver program can read the accumulator’s value,using itsvalue method.

The code below shows an accumulator being used to add up the elements of an array:

scala>valaccum=sc.longAccumulator("My Accumulator")accum:org.apache.spark.util.LongAccumulator=LongAccumulator(id:0,name:Some(MyAccumulator),value:0)scala>sc.parallelize(Array(1,2,3,4)).foreach(x=>accum.add(x))...10/09/2918:41:08INFOSparkContext:Tasksfinishedin0.317106sscala>accum.valueres2:Long=10

While this code used the built-in support for accumulators of type Long, programmers can alsocreate their own types by subclassingAccumulatorV2.The AccumulatorV2 abstract class has several methods which one has to override:reset for resettingthe accumulator to zero,add for adding another value into the accumulator,merge for merging another same-type accumulator into this one. Other methods that must be overriddenare contained in theAPI documentation. For example, supposing we had aMyVector classrepresenting mathematical vectors, we could write:

classVectorAccumulatorV2extendsAccumulatorV2[MyVector,MyVector]{privatevalmyVector:MyVector=MyVector.createZeroVectordefreset():Unit={myVector.reset()}defadd(v:MyVector):Unit={myVector.add(v)}...}// Then, create an Accumulator of this type:valmyVectorAcc=newVectorAccumulatorV2// Then, register it into spark context:sc.register(myVectorAcc,"MyVectorAcc1")

Note that, when programmers define their own type of AccumulatorV2, the resulting type can be different than that of the elements added.

A numeric accumulator can be created by callingSparkContext.longAccumulator() orSparkContext.doubleAccumulator()to accumulate values of type Long or Double, respectively. Tasks running on a cluster can then add to it usingtheadd method. However, they cannot read its value. Only the driver program can read the accumulator’s value,using itsvalue method.

The code below shows an accumulator being used to add up the elements of an array:

LongAccumulatoraccum=jsc.sc().longAccumulator();sc.parallelize(Arrays.asList(1,2,3,4)).foreach(x->accum.add(x));// ...// 10/09/29 18:41:08 INFO SparkContext: Tasks finished in 0.317106 saccum.value();// returns 10

While this code used the built-in support for accumulators of type Long, programmers can alsocreate their own types by subclassingAccumulatorV2.The AccumulatorV2 abstract class has several methods which one has to override:reset for resettingthe accumulator to zero,add for adding another value into the accumulator,merge for merging another same-type accumulator into this one. Other methods that must be overriddenare contained in theAPI documentation. For example, supposing we had aMyVector classrepresenting mathematical vectors, we could write:

classVectorAccumulatorV2implementsAccumulatorV2<MyVector,MyVector>{privateMyVectormyVector=MyVector.createZeroVector();publicvoidreset(){myVector.reset();}publicvoidadd(MyVectorv){myVector.add(v);}...}// Then, create an Accumulator of this type:VectorAccumulatorV2myVectorAcc=newVectorAccumulatorV2();// Then, register it into spark context:jsc.sc().register(myVectorAcc,"MyVectorAcc1");

Note that, when programmers define their own type of AccumulatorV2, the resulting type can be different than that of the elements added.

Warning: When a Spark task finishes, Spark will try to merge the accumulated updates in this task to an accumulator.If it fails, Spark will ignore the failure and still mark the task successful and continue to run other tasks. Hence,a buggy accumulator will not impact a Spark job, but it may not get updated correctly although a Spark job is successful.

For accumulator updates performed insideactions only, Spark guarantees that each task’s update to the accumulatorwill only be applied once, i.e. restarted tasks will not update the value. In transformations, users should be awareof that each task’s update may be applied more than once if tasks or job stages are re-executed.

Accumulators do not change the lazy evaluation model of Spark. If they are being updated within an operation on an RDD, their value is only updated once that RDD is computed as part of an action. Consequently, accumulator updates are not guaranteed to be executed when made within a lazy transformation likemap(). The below code fragment demonstrates this property:

accum=sc.accumulator(0)defg(x):accum.add(x)returnf(x)data.map(g)# Here, accum is still 0 because no actions have caused the `map` to be computed.
valaccum=sc.longAccumulatordata.map{x=>accum.add(x);x}// Here, accum is still 0 because no actions have caused the map operation to be computed.
LongAccumulatoraccum=jsc.sc().longAccumulator();data.map(x->{accum.add(x);returnf(x);});// Here, accum is still 0 because no actions have caused the `map` to be computed.

Deploying to a Cluster

Theapplication submission guide describes how to submit applications to a cluster.In short, once you package your application into a JAR (for Java/Scala) or a set of.py or.zip files (for Python),thebin/spark-submit script lets you submit it to any supported cluster manager.

Launching Spark jobs from Java / Scala

Theorg.apache.spark.launcherpackage provides classes for launching Spark jobs as child processes using a simple Java API.

Unit Testing

Spark is friendly to unit testing with any popular unit test framework.Simply create aSparkContext in your test with the master URL set tolocal, run your operations,and then callSparkContext.stop() to tear it down.Make sure you stop the context within afinally block or the test framework’stearDown method,as Spark does not support two contexts running concurrently in the same program.

Where to Go from Here

You can see someexample Spark programs on the Spark website.In addition, Spark includes several samples in theexamples directory(Python,Scala,Java,R).You can run Java and Scala examples by passing the class name to Spark’sbin/run-example script; for instance:

./bin/run-example SparkPi

For Python examples, usespark-submit instead:

./bin/spark-submit examples/src/main/python/pi.py

For R examples, usespark-submit instead:

./bin/spark-submit examples/src/main/r/dataframe.R

For help on optimizing your programs, theconfiguration andtuning guides provide information on best practices. They are especially important formaking sure that your data is stored in memory in an efficient format.For help on deploying, thecluster mode overview describes the components involvedin distributed operation and supported cluster managers.

Finally, full API documentation is available inPython,Scala,Java andR.


[8]ページ先頭

©2009-2025 Movatter.jp