Spark Shared Variables
In Apache Spark, the shared variables allow multiple tasks to share the data efficiently on each worker node while processing the job. Spark has two types of shared variables Broadcast variables and Accumulators.
Broadcast Variables
In Spark RDD and DataFrame, Broadcast variables are read-only shared variables that are cached and available on all nodes in a cluster in order to access or use by the tasks. Instead of sending this data along with every task, spark distributes broadcast variables to the machine using efficient broadcast algorithms to reduce communication costs.
Use case
Let's assume you are getting a two-letter country state code in a file and you want to transform it to a full state name, (for example CA to California, NY to New York, etc.) by doing a lookup to reference mapping. In some instances, this data could be large and you may have many such lookups (like zip code).
Instead of distributing this information along with each task over the network (overhead and time-consuming), we can use the broadcast variable to cache this lookup info on each machine, and tasks use this cached info while executing the transformations.
How does Spark Broadcast work?
Broadcast variables are used in the same way for RDD, DataFrame, and Dataset. In this lesson, I will primarily focus on RDD.
When you run a Spark RDD job that has the Broadcast variables defined and used, Spark does the following.
- Spark breaks the job into stages that have distributed shuffling and actions are executed within the stage.
- Later Stages are also broken into tasks
- Spark broadcasts the common data (reusable) needed by tasks within each stage.
- The broadcasted data is cached in serialized format and deserialized before executing each task.
You should be creating and using broadcast variables for data that is shared across multiple stages and tasks.
Creating Broadcast variable
The Spark Broadcast is created using the broadcast(v) method of the SparkContext class. This method takes the argument v that you want to broadcast.
In Spark shell
scala> val broadcastVar = sc.broadcast(Array(0, 1, 2, 3))
broadcastVar: org.apache.spark.broadcast.Broadcast[Array[Int]] = Broadcast(0)
scala> broadcastVar.value res0: Array[Int] = Array(0, 1, 2, 3)
Note that broadcast variables are not sent to executors when you call sc.broadcast(variable) statement, but, they will be sent to executors when they are first used.
Spark RDD Broadcast Variable Example
Below is a very simple example of how to use broadcast variables on RDD. This example defines commonly used data (country and states) in a Map variable and distributes the variable using SparkContext.broadcast() and then uses these variables on RDD map() transformation.
// Imports
import org.apache.spark.sql.SparkSession
object RDDBroadcast extends App {
// Create SparkSession
val spark = SparkSession.builder().appName("AIStudyLabs.com").master("local").getOrCreate()
val states = Map(("NY","New York"),("CA","California"),("FL","Florida"))
val countries = Map(("USA","United States of America"),("IN","India"))
// Create broadcast variable
val broadcastStates = spark.sparkContext.broadcast(states)
val broadcastCountries = spark.sparkContext.broadcast(countries)
// Create RDD
val data = Seq(("James","Smith","USA","CA"),("Michael","Rose","USA","NY"),
("Robert","Williams","USA","CA"),("Maria","Jones","USA","FL") )
val rdd = spark.sparkContext.parallelize(data)
// RDD Transformation
val rdd2 = rdd.map(f=>{
val country = f._3
val state = f._4
// Using broadcast variables
val fullCountry = broadcastCountries.value.get(country).get
val fullState = broadcastStates.value.get(state).get
(f._1,f._2,fullCountry,fullState)
})
// Print RDD
println(rdd2.collect().mkString("\n"))
}
