"<small><i>This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/data-science-ipython-notebooks).</i></small>"
"Follow the instructions provided [here](http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/) to configure IPython Notebook Support for PySpark."
"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.\n",
"\n",
"There are two types of RDD operations:\n",
"* Actions: Returns values, data is not processed in an RDD until an action is preformed\n",
"* Transformations: Defines a new RDD based on the current\n"
"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:"
"for (user_id, (user_info, count)) in user_actions_with_profiles.take(10):\n",
" print user_id, count, user_info"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running Spark on a Cluster"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Start the standalone cluster's Master and Worker daemons:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"!sudo service spark-master start\n",
"!sudo service spark-worker start"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Stop the standalone cluster's Master and Worker daemons:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"!sudo service spark-master stop\n",
"!sudo service spark-worker stop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Restart the standalone cluster's Master and Worker daemons:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"!sudo service spark-master stop\n",
"!sudo service spark-worker stop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"View the Spark standalone cluster UI:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"http://localhost:18080//"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Start the Spark shell and connect to the cluster:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"!MASTER=spark://localhost:7077 pyspark"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Confirm you are connected to the correct master:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"sc.master"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Viewing the Spark Application UI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the following [reference](http://spark.apache.org/docs/1.2.0/monitoring.html):\n",
"\n",
"Every SparkContext launches a web UI, by default on port 4040, that displays useful information about the application. This includes:\n",
"\n",
"A list of scheduler stages and tasks\n",
"A summary of RDD sizes and memory usage\n",
"Environmental information.\n",
"Information about the running executors\n",
"\n",
"You can access this interface by simply opening http://<driver-node>: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).\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"http://localhost:4040/"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Working with Partitions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the following [reference](http://blog.cloudera.com/blog/2014/09/how-to-translate-from-mapreduce-to-apache-spark/):\n",
"\n",
"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:"
"* 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.\n",
"* map() is a transformation, rather than an operation, and is lazily evaluated. The connection can’t be closed immediately here.\n",
"* Even so, it would only close the connection on the driver, not necessarily freeing resources allocated by serialized copies."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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 an RDD saves the data in memory. Caching is a suggestion to Spark as it is memory dependent.\n",
"\n",
"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.\n",
"\n",
"* cache() stores data in memory\n",
"* persist() stores data in MEMORY_ONLY, MEMORY_AND_DISK (spill to disk), and DISK_ONLY\n",
"\n",
"Disk memory is stored on the node, not on HDFS.\n",
"\n",
"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.\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Cache RDD to memory\n",
"my_data.cache()\n",
"\n",
"# Persist RDD to both memory and disk (if memory is not enough), with replication of 2\n",
"my_data.persist(MEMORY_AND_DISK_2)\n",
"\n",
"# Unpersist RDD, removing it from memory and disk\n",
"my_data.unpersist()\n",
"\n",
"# Change the persistence level after unpersist\n",
"my_data.persist(MEMORY_AND_DISK)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Checkpointing RDDs\n",
"\n",
"Caching maintains RDD lineage, providing resilience. If the lineage is very long, it is possible to get a stack overflow.\n",
"\n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a checkpoint and perform an action by calling count() to materialize the checkpoint and save it to the checkpoint file:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Enable checkpointing by setting the checkpoint directory, \n",
"# which will contain all checkpoints for the given data:\n",
"Get a DStream from a streaming data source (text from a socket):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"val logs = ssc.socketTextStream(hostname, port)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"DStreams support regular transformations such as map, flatMap, and filter, and pair transformations such as reduceByKey, groupByKey, and joinByKey.\n",
"\n",
"Apply a DStream operation to each batch of RDDs (count up requests by user id, reduce by key to get the count):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"val requests = my_stream\n",
" .map(line => (line.split(\" \")(2), 1))\n",
" .reduceByKey((x, y) => x + y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The transform(function) method creates a new DStream by executing the input function on the RDDs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"val sorted_requests = requests\n",
" .map(pair => pair.swap)\n",
" .transform(rdd => rdd.sortByKey(false))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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):"