问题
I have the following code to detect most used top level domain from events. I use it to get date via Spark SQL.
Functions themselves are tested and work fine. I use Amazon EMR and spark-shell. When spark sends tasks to nodes, almost immediately, I receive a long stack trace and "SparkException: Task not serializable" in the end without anything specific. What's the deal here?
import scala.io.Source
val suffixesStr =
Source.fromURL("https://publicsuffix.org/list/public_suffix_list.dat").mkString
val suffList =
suffixesStr.lines.filter(line => !line.startsWith("//") && line.trim() != "")
val suffListRDD = sc.parallelize(suffList.toList).collect()
val cleanDomain = (domain: String) => {
var secLevelSuffix =
suffListRDD.find(suffix => domain.endsWith("."+suffix) && suffix.contains("."))
var regex = """[^.]+\.[^.]+$""".r
if (!secLevelSuffix.isEmpty){
regex = """[^.]+\.[^.]+\.[^.]+$""".r
}
var cleanDomain = regex.findFirstMatchIn(domain).map(_ group 0)
cleanDomain.getOrElse("")
}
val getDomain = (url: String) => {
val domain = """(?i)^(?:(?:https?):\/\/)?(?:(?:www|www1|www2|www3)\.)?([^:?#/\s]+)""".r.findFirstMatchIn(url).map(_ group 1)
var res = domain.getOrElse("")
res = res.toLowerCase()
if (res.contains("google.com")){
res = res.replace("google.com.br", "google.com")
}else{
res = cleanDomain(res)
}
res
}
sqlContext.udf.register("getDomain", getDomain)
val domains = sqlContext.sql("SELECT count(*) c, domain from (SELECT getDomain(page_url) as domain FROM events) t group by domain order by c desc")
domains.take(20).foreach(println)
回答1:
When you define an RDD programatically like in this case, don't forget to mark things that won't be replicated to worker nodes as @transient.
In you case:
@transient val suffixesStr = ...
@transient val suffList = ...
来源:https://stackoverflow.com/questions/32203679/apache-spark-sparkexception-task-not-serializable-in-spark-shell-for-rdd-con