top

Search

Apache Spark Tutorial

IntroductionIn this section we will look at the Spark Core programming APIs. These are the basic transformations and actions which we will use across applications. The RDDs API form the basic building blocks of any Spark applications. We will also look at creating RDDs using the Spark shell and see how we can execute transformations and actions on those RDDs.Spark Core is the backbone of the whole Spark project. It provides all the major functionalities and the building blocks for all the other parts of Spark. It takes care of task dispatching, input-output operations and scheduling of the processes. Spark Core is the distributed execution engine and all other functionalities are built on top of it. All the basic functionality of Apache Spark like task scheduling, fault tolerance, in-memory computation, memory management, monitoring, is provided by Spark Core. Spark Core also provides basic connectivity with external data sources like HBase, Cassandra, Amazon S3, HDFS, etc.Spark Shell:Spark shell is an interactive shell and a powerful tool to start analyzing data on Spark. It is available in Scala, R and Python programming languages.Open Spark Shell:Spark shell in Scala can be opened by executing the command “spark-shell” on the command line.For python spark shell use the command “pyspark”Create simple RDD:A simple RDD can be created by reading a file from external storage or by creating on the command line itself like below:Spark has Transformations and Actions APIs to manipulate RDDs and process data as per user’s requirements. We will go through some of the common transformations and actions below.RDD Transformations:Explanation: Transformations are operations on RDD which produce another RDD. This is the simple definition of a transformation. Since Spark is lazy in nature, RDD transformations do not lead to actual computation, but it just creates a logical step in the DAG i.e. creates a dependency with its parent RDD. So effectively transformations are just steps that tell how to get the data, but it does not do anything unless action is called in the program.List of RDD transformations:map(func): Calling map on any RDD returns a MappedRDD object. This object has the same partitions and preferred locations as its parentbut applies the function passed to map to the parent’s records in its iterator method.filter(func): Return a new dataset formed by selecting those elements of the source on which funcreturns true.flatMap(func): Similar to a map, but each input item can be mapped to 0 or more output items (so funcshould return a Seq rather than a single item).mapPartitions(func):Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.mapPartitionsWithIndex(func):Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.sample(withReplacement, fraction, seed):Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.union(otherDataset):Return a new dataset that contains the union of the elements in the source dataset and the argument.intersection(otherDataset): Return a new RDD that contains the intersection of elements in the source dataset and the argument.distinct([numTasks]): Return a new dataset that contains the distinct elements of the source dataset.groupByKey([numTasks]): When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance.Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numPartitions argument to set a different number of tasks.reduceByKey(func, [numTasks]):When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.aggregateByKey(zeroValue)(seqOp,combOp, [numTasks]):When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. It allows an aggregated value type that is different than the input value typewhile avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.sortByKey([ascending], [numTasks]):When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the booleanascending argument.join(otherDataset, [numTasks]): Joining two RDDs may lead to either two narrow dependencies (if they are both hash/range partitioned with the same partitioner), two wide dependencies, or a mix (if one parent has a partitioner and one does not). In either case, the output RDD has a partitioner (either one inherited from the parents or a default hash partitioner). When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin.cogroup(otherDataset, [numTasks]):When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called groupWith.cartesian(otherDataset):When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).pipe(command, [envVars]):Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.coalesce(numPartitions):Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.repartition(numPartitions):Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.repartitionAndSortWithinPartitions(partitioner):Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.Actions: Actions are the operations in which the result is anything other than an RDD.The values calculated in actions are sent to the Driver or to the external storagelikeHDFS. So basically Actions bring Spark laziness into motion. When an action is called, Executors execute the task assigned to them and pass on the result to the Driver or write the result to storage thus completing the task.reduce(func):Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.collect():Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.count():Return the number of elements in the dataset.first():Return the first element of the dataset (similar to take(1)).take(n):Return an array with the first n elements of the dataset.takeSample (withReplacement,num, [seed]):Return an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.takeOrdered(n, [ordering]):Return the first n elements of the RDD using either their natural order or a custom comparator.saveAsTextFile(path):Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file.saveAsSequenceFile(path) (Java and Scala):Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that 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 function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems.Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details.ConclusionIn this section we looked at some of the main APIs used for basic data processing in Apache Spark.
logo

Apache Spark Tutorial

Apache Spark Core Programming

Introduction

In this section we will look at the Spark Core programming APIs. These are the basic transformations and actions which we will use across applications. The RDDs API form the basic building blocks of any Spark applications. We will also look at creating RDDs using the Spark shell and see how we can execute transformations and actions on those RDDs.

Spark Core is the backbone of the whole Spark project. It provides all the major functionalities and the building blocks for all the other parts of Spark. It takes care of task dispatching, input-output operations and scheduling of the processes. Spark Core is the distributed execution engine and all other functionalities are built on top of it. All the basic functionality of Apache Spark like task scheduling, fault tolerance, in-memory computation, memory management, monitoring, is provided by Spark Core. Spark Core also provides basic connectivity with external data sources like HBase, Cassandra, Amazon S3, HDFS, etc.

  • Spark Shell:

Spark shell is an interactive shell and a powerful tool to start analyzing data on Spark. It is available in Scala, R and Python programming languages.

  • Open Spark Shell:

Spark shell in Scala can be opened by executing the command “spark-shell” on the command line.

For python spark shell use the command “pyspark”

  • Create simple RDD:

A simple RDD can be created by reading a file from external storage or by creating on the command line itself like below:

Create simple RDD

Spark has Transformations and Actions APIs to manipulate RDDs and process data as per user’s requirements. We will go through some of the common transformations and actions below.

  • RDD Transformations:

Explanation: Transformations are operations on RDD which produce another RDD. This is the simple definition of a transformation. Since Spark is lazy in nature, RDD transformations do not lead to actual computation, but it just creates a logical step in the DAG i.e. creates a dependency with its parent RDD. So effectively transformations are just steps that tell how to get the data, but it does not do anything unless action is called in the program.

List of RDD transformations:

  • map(func): Calling map on any RDD returns a MappedRDD object. This object has the same partitions and preferred locations as its parentbut applies the function passed to map to the parent’s records in its iterator method.
  • filter(func): Return a new dataset formed by selecting those elements of the source on which funcreturns true.
  • flatMap(func): Similar to a map, but each input item can be mapped to 0 or more output items (so funcshould return a Seq rather than a single item).
  • mapPartitions(func):Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> => Iterator<U> when running on an RDD of type T.
  • mapPartitionsWithIndex(func):Similar to mapPartitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) => Iterator<U> when running on an RDD of type T.
  • sample(withReplacement, fraction, seed):Sample a fraction fraction of the data, with or without replacement, using a given random number generator seed.
  • union(otherDataset):Return a new dataset that contains the union of the elements in the source dataset and the argument.
  • intersection(otherDataset): Return a new RDD that contains the intersection of elements in the source dataset and the argument.
  • distinct([numTasks]): Return a new dataset that contains the distinct elements of the source dataset.
  • groupByKey([numTasks]): When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.

Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance.

Note: By default, the level of parallelism in the output depends on the number of partitions of the parent RDD. You can pass an optional numPartitions argument to set a different number of tasks.

  • reduceByKey(func, [numTasks]):When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V,V) => V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
  • aggregateByKey(zeroValue)(seqOp,combOp, [numTasks]):When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. It allows an aggregated value type that is different than the input value typewhile avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
  • sortByKey([ascending], [numTasks]):When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the booleanascending argument.
  • join(otherDataset, [numTasks]): Joining two RDDs may lead to either two narrow dependencies (if they are both hash/range partitioned with the same partitioner), two wide dependencies, or a mix (if one parent has a partitioner and one does not). In either case, the output RDD has a partitioner (either one inherited from the parents or a default hash partitioner). When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin.
  • cogroup(otherDataset, [numTasks]):When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called groupWith.
  • cartesian(otherDataset):When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).
  • pipe(command, [envVars]):Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.
  • coalesce(numPartitions):Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.
  • repartition(numPartitions):Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.
  • repartitionAndSortWithinPartitions(partitioner):Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.
  • Actions: Actions are the operations in which the result is anything other than an RDD.

The values calculated in actions are sent to the Driver or to the external storagelikeHDFS. So basically Actions bring Spark laziness into motion. When an action is called, Executors execute the task assigned to them and pass on the result to the Driver or write the result to storage thus completing the task.

  • reduce(func):Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.
  • collect():Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
  • count():Return the number of elements in the dataset.
  • first():Return the first element of the dataset (similar to take(1)).
  • take(n):Return an array with the first n elements of the dataset.
  • takeSample (withReplacement,num, [seed]):Return an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.
  • takeOrdered(n, [ordering]):Return the first n elements of the RDD using either their natural order or a custom comparator.
  • saveAsTextFile(path):Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file.
  • saveAsSequenceFile(path) (Java and Scala):Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that 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 function func on each element of the dataset. This is usually done for side effects such as updating an Accumulator or interacting with external storage systems.

Note: modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details.

Conclusion

In this section we looked at some of the main APIs used for basic data processing in Apache Spark.

Leave a Reply

Your email address will not be published. Required fields are marked *