0

我有一个 hadoopFiles 对象,它是从sc.newAPIHadoopFile.

scala> hadoopFiles
res1: org.apache.spark.rdd.RDD[(org.apache.hadoop.io.LongWritable, org.apache.hadoop.io.Text)] = UnionRDD[64] at union at <console>:24

我打算使用操作遍历 hadoopFiles 中的所有行并对其进行过滤,其中if应用检查并将引发异常:

scala> val rowRDD = hadoopFiles.map(line =>
     |           line._2.toString.split("\\^") map {
     |             field => {
     |               var pair = field.split("=", 2)
     |               if(pair.length == 2)
     |                 (pair(0) -> pair(1))
     |             }
     |           } toMap
     |         ).map(kvs => Row(kvs("uuid"), kvs("ip"), kvs("plt").trim))
<console>:33: error: Cannot prove that Any <:< (T, U).
                 } toMap
                   ^

但是,如果我删除该if(pair.length == 2)部分,它会正常工作:

scala>     val rowRDD = hadoopFiles.map(line =>
     |           line._2.toString.split("\\^") map {
     |             field => {
     |               var pair = field.split("=", 2)
     |               (pair(0) -> pair(1))
     |             }
     |           } toMap
     |         ).map(kvs => Row(kvs("uuid"), kvs("ip"), kvs("plt").trim))
warning: there was one feature warning; re-run with -feature for details
rowRDD: org.apache.spark.rdd.RDD[org.apache.spark.sql.catalyst.expressions.Row] = MappedRDD[66] at map at <console>:33

谁能告诉我这种现象的原因,并告诉我应用该if声明的正确方法。非常感谢!

PS我们可以用这个简化的例子来测试:

"1=a^2=b^3".split("\\^") map {
            field => {
              var pair = field.split("=", 2)
              if(pair.length == 2)
                pair(0) -> pair(1)
              else
                return
            }
          } toMap
4

2 回答 2

3

要映射集合并仅保留一些映射元素,您可以使用flatMap. flatMap接受一个返回集合的函数,例如实例 an Option。现在if表达式需要有一个else返回空的部分Option,即None

scala> val rowRDD = hadoopFiles.map(line =>
     |           line._2.toString.split("\\^") flatMap {
     |             field => {
     |               var pair = field.split("=", 2)
     |               if (pair.length == 2)
     |                 Some(pair(0) -> pair(1))
     |               else
     |                 None
     |             }
     |           } toMap
     |         ).map(kvs => Row(kvs("uuid"), kvs("ip"), kvs("plt").trim))
于 2015-02-04T01:12:23.580 回答
1

您可以使用collect

val res = "1=a^2=b^3".split("\\^") collect {
  _.split("=", 2) match {
    case Array(a, b) => a -> b
  }
} toMap

println(res) // Map(1 -> a, 2 -> b)

在您的特定情况下,会发生以下情况:

case class Row(uuid: String, ip: String, plt: String)
val hadoopFiles = List(("", "uuid=a^ip=b^plt"))

val rowRDD = hadoopFiles.map(line =>
  line._2.toString.split("\\^") map {
    field =>
      {
        var pair = field.split("=", 2)
        val res = if (pair.length == 2)
          (pair(0) -> pair(1))
        res  // res: Any (common super class for (String, String)
             // which is Tuple2 and Unit (result for case when 
             // pair.length != 2)
      }
  } /* <<< returns Array[Any] */ /*toMap*/ ) 
  //.map(kvs => Row(kvs("uuid"), kvs("ip"), kvs("plt").trim))

内部映射的结果是Any,映射产生 Array[Any]。如果您查看toMap定义,您将看到:

  def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
    val b = immutable.Map.newBuilder[T, U]
    for (x <- self)
      b += x // <<< implicit conversion from each `x` of class `A` in `self`
             // to (T, U) because we have `implicit ev: A <:< (T, U)`
    b.result()
  }

对于您来说,在当前上下文中Array[Any]没有隐式转换。因此,您的代码失败。如果您添加其他替代方案:Any(T, U)

  val rowRDD = hadoopFiles.map(line =>
    (line._2.toString.split("\\^") map {
      field =>
        {
          var pair = field.split("=", 2)
          val res = if (pair.length == 2)
            (pair(0) -> pair(1))
          else ("" -> "") // dummy, just for demo
          res // res: (String, String)
        }
    } toMap) withDefaultValue ("") 
           /*withDefaultValue just to avoid Exception for this demo*/ )
    .map(kvs => Row(kvs("uuid"), kvs("ip"), kvs("plt").trim))

  println(rowRDD) // List(Row(a,b,))

在这里,您的结果将是 Array[(String, String)] 并且存在从(String, String)to的隐式转换(T, U)。所以代码编译并工作。

于 2015-02-04T08:11:47.513 回答