📚 The CoCalc Library - books, templates and other resources
License: OTHER
This notebook was prepared by Donne Martin. Source and license info is on GitHub.
Spark
IPython Notebook Setup
Python Shell
DataFrames
RDDs
Pair RDDs
Running Spark on a Cluster
Viewing the Spark Application UI
Working with Partitions
Caching RDDs
Checkpointing RDDs
Writing and Running a Spark Application
Configuring Spark Applications
Streaming
Streaming with States
Broadcast Variables
Accumulators
IPython Notebook Setup
The dev-setup repo contains scripts to install Spark and to automate the its integration with IPython Notebook through the pydata.sh script.
You can also follow the instructions provided here to configure IPython Notebook Support for PySpark with Python 2.
To run Python 3 with Spark 1.4+, check out the following posts on Stack Overflow or Reddit.
Python Shell
Start the pyspark shell (REPL):
View the spark context, the main entry point to the Spark API:
DataFrames
From the following reference:
A DataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database or a data frame in R/Python, but with richer optimizations under the hood.
Create a DataFrame from JSON files on S3:
Create a new DataFrame that contains “young users” only:
Alternatively, using Pandas-like syntax:
Increment everybody’s age by 1:
Count the number of young users by gender:
Join young users with another DataFrame called logs:
Count the number of users in the young DataFrame:
Convert Spark DataFrame to Pandas:
Create a Spark DataFrame from Pandas:
Given the Spark Context, create a SQLContext:
Create a DataFrame based on the content of a file:
Display the content of the DataFrame:
Print the schema:
Select a column:
Create a DataFrame with rows matching a given filter:
Aggregate the results and count:
Convert a RDD to a DataFrame (by inferring the schema):
Register the DataFrame as a table:
Run a SQL Query on a DataFrame registered as a table:
RDDs
Note: RDDs are included for completeness. In Spark 1.3, DataFrames were introduced which are recommended over RDDs. Check out the DataFrames announcement for more info.
Resilient Distributed Datasets (RDDs) are the fundamental unit of data in Spark. RDDs can be created from a file, from data in memory, or from another RDD. RDDs are immutable.
There are two types of RDD operations:
Actions: Returns values, data is not processed in an RDD until an action is preformed
Transformations: Defines a new RDD based on the current
Create an RDD from the contents of a directory:
Count the number of lines in the data:
Return all the elements of the dataset as an array--this is usually more useful after a filter or other operation that returns a sufficiently small subset of the data:
Return the first 10 lines in the data:
Create an RDD with lines matching the given filter:
Chain a series of commands:
Create a new RDD mapping each line to an array of words, taking only the first word of each array:
Output each word in first_words:
Save the first words to a text file:
Pair RDDs
Pair RDDs contain elements that are key-value pairs. Keys and values can be any type.
Given a log file with the following space deilmited format: [date_time, user_id, ip_address, action], map each request to (user_id, 1):
Show the top 5 users by count, sorted in descending order:
Group IP addresses by user id:
Given a user table with the following csv format: [user_id, user_info0, user_info1, ...], map each line to (user_id, [user_info...]):
Inner join the user_actions and user_profile RDDs:
Show the joined table:
Running Spark on a Cluster
Start the standalone cluster's Master and Worker daemons:
Stop the standalone cluster's Master and Worker daemons:
Restart the standalone cluster's Master and Worker daemons:
View the Spark standalone cluster UI:
Start the Spark shell and connect to the cluster:
Confirm you are connected to the correct master:
Viewing the Spark Application UI
From the following reference:
Every SparkContext launches a web UI, by default on port 4040, that displays useful information about the application. This includes:
A list of scheduler stages and tasks A summary of RDD sizes and memory usage Environmental information. Information about the running executors
You can access this interface by simply opening http://[removed]:4040 in a web browser. If multiple SparkContexts are running on the same host, they will bind to successive ports beginning with 4040 (4041, 4042, etc).
Note that this information is only available for the duration of the application by default. To view the web UI after the fact, set spark.eventLog.enabled to true before starting the application. This configures Spark to log Spark events that encode the information displayed in the UI to persisted storage.
Working with Partitions
From the following reference:
The Spark map() and flatMap() methods only operate on one input at a time, and provide no means to execute code before or after transforming a batch of values. It looks possible to simply put the setup and cleanup code before and after a call to map() in Spark:
However, this fails for several reasons:
It puts the object dbConnection into the map function’s closure, which requires that it be serializable (for example, by implementing java.io.Serializable). An object like a database connection is generally not serializable.
map() is a transformation, rather than an operation, and is lazily evaluated. The connection can’t be closed immediately here.
Even so, it would only close the connection on the driver, not necessarily freeing resources allocated by serialized copies.
In fact, neither map() nor flatMap() is the closest counterpart to a Mapper in Spark — it’s the important mapPartitions() method. This method does not map just one value to one other value, but rather maps an Iterator of values to an Iterator of other values. It’s like a “bulk map” method. This means that the mapPartitions() function can allocate resources locally at its start, and release them when done mapping many values.
Caching RDDs
Caching an RDD saves the data in memory. Caching is a suggestion to Spark as it is memory dependent.
By default, every RDD operation executes the entire lineage. Caching can boost performance for datasets that are likely to be used by saving this expensive recomputation and is ideal for iterative algorithms or machine learning.
cache() stores data in memory
persist() stores data in MEMORY_ONLY, MEMORY_AND_DISK (spill to disk), and DISK_ONLY
Disk memory is stored on the node, not on HDFS.
Replication is possible by using MEMORY_ONLY_2, MEMORY_AND_DISK_2, etc. If a cached partition becomes unavailable, Spark recomputes the partition through the lineage.
Serialization is possible with MEMORY_ONLY_SER and MEMORY_AND_DISK_SER. This is more space efficient but less time efficient, as it uses Java serialization by default.
Checkpointing RDDs
Caching maintains RDD lineage, providing resilience. If the lineage is very long, it is possible to get a stack overflow.
Checkpointing saves the data to HDFS, which provide fault tolerant storage across nodes. HDFS is not as fast as local storage for both reading and writing. Checkpointing is good for long lineages and for very large data sets that might not fit on local storage. Checkpointing removes lineage.
Create a checkpoint and perform an action by calling count() to materialize the checkpoint and save it to the checkpoint file:
Writing and Running a Spark Application
Create a Spark application to count the number of text files:
Submit the script to Spark for processing:
Configuring Spark Applications
Run a Spark app and set the configuration options in the command line:
Configure spark.conf:
Run a Spark app and set the configuration options through spark.conf:
Set the config options programmatically:
Set logging levels located in the following file, or place a copy in your pwd:
Streaming
Start the Spark Shell locally with at least two threads (need a minimum of two threads for streaming, one for receiving, one for processing):
Create a StreamingContext (similar to SparkContext in core Spark) with a batch duration of 1 second:
Get a DStream from a streaming data source (text from a socket):
DStreams support regular transformations such as map, flatMap, and filter, and pair transformations such as reduceByKey, groupByKey, and joinByKey.
Apply a DStream operation to each batch of RDDs (count up requests by user id, reduce by key to get the count):
The transform(function) method creates a new DStream by executing the input function on the RDDs.
foreachRDD(function) performs a function on each RDD in the DStream (map is like a shortcut not requiring you to get the RDD first before doing an operation):
Save the DStream result part files with the given folder prefix, the actual folder will be /dir/requests-timestamp0/:
Start the execution of all DStreams:
Wait for all background threads to complete before ending the main thread:
Streaming with States
Enable checkpointing to prevent infinite lineages:
Compute a DStream based on the previous states plus the current state:
Compute a DStream based Sliding window, every 30 seconds, count requests by user over the last 5 minutes:
Collect statistics with the StreamingListener API:
Broadcast Variables
Read in list of items to broadcast from a local file:
Broadcast the target list to all workers:
Filter based on the broadcast list:
Accumulators
Create an accumulator:
Count the number of txt files in the RDD:
Count the number of file types encountered: