Apache Spark: “SparkException: Task not serializable” in spark-shell for RDD constructed manually

…衆ロ難τιáo~ 提交于 2019-12-13 07:52:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!