2

我将 Spark 2.1.1 与 Scala 2.11.6 一起使用。我收到以下错误。我没有使用任何案例类。

java.lang.UnsupportedOperationException: No Encoder found for scala.collection.immutable.Set[String]
 field (class: "scala.collection.immutable.Set", name: "_2")
 field (class: "scala.Tuple2", name: "_2")
 root class: "scala.Tuple2"

以下代码部分是堆栈跟踪指向的位置。

val tweetArrayRDD = nameDF.select("namedEnts", "text", "storylines")
    .flatMap {
    case Row(namedEnts: Traversable[(String, String)], text: String, storylines: Traversable[String]) =>
      Option(namedEnts) match {
        case Some(x: Traversable[(String, String)]) =>
          //println("In flatMap:" + x + " ~~&~~ " + text + " ~~&~~ " + storylines)
          namedEnts.map((_, (text, storylines.toSet)))
        case _ => //println("In flatMap: blahhhh")
          Traversable()
      }
    case _ => //println("In flatMap: fooooo")
      Traversable()
  }
  .rdd.aggregateByKey((Set[String](), Set[String]()))((a, b) => (a._1 + b._1, a._2 ++ b._2), (a, b) => (a._1 ++ b._1, a._2 ++ b._2))
  .map { (s: ((String, String), (Set[String], Set[String]))) => {
    //println("In map: " + s)
    (s._1, (s._2._1.toSeq, s._2._2.toSeq))
  }}
4

1 回答 1

7

这里的问题是 Spark 没有提供Set开箱即用的编码器(它确实为“原始”、序列、数组和其他支持类型的产品提供了编码器)。

您可以尝试使用这个出色的答案来创建自己的编码器Set[String](更准确地说,是您正在使用的类型的编码器Traversable[((String, String), (String, Set[String]))],其中包含 a Set[String]),或者Seq您可以通过使用 a而不是a 来解决此问题Set

// ...
case Some(x: Traversable[(String, String)]) =>
  //println("In flatMap:" + x + " ~~&~~ " + text + " ~~&~~ " + storylines)
  namedEnts.map((_, (text, storylines.toSeq.distinct)))
// ...

(我是distinct用来模仿Set行为的;也可以试试.toSet.toSeq

更新:根据您对 Spark 1.6.2 的评论 - 不同之处在于,在 1.6.2 中,Dataset.flatMap返回 anRDD而不是 a Dataset,因此不需要对您提供的函数返回的结果进行编码;因此,这确实带来了另一个很好的解决方法 - 您可以通过在操作之前显式切换到使用 RDD 来轻松模拟这种行为flatMap

nameDF.select("namedEnts", "text", "storylines")
  .rdd
  .flatMap { /*...*/ } // use your function as-is, it can return Set[String]
  .aggregateByKey( /*...*/ )
  .map( /*...*/ )
于 2017-07-10T20:48:24.240 回答