Apache Spark:处理RDD中的Option / Some / None

时间:2015-03-17 15:49:00

标签: scala exception apache-spark scala-option

我正在映射HBase表,每个HBase行生成一个RDD元素。但是,有时行有坏数据(在解析代码中抛出NullPointerException),在这种情况下我只想跳过它。

我的初始映射器返回Option表示它返回0或1个元素,然后过滤Some,然后获取包含的值:

// myRDD is RDD[(ImmutableBytesWritable, Result)]
val output = myRDD.
  map( tuple => getData(tuple._2) ).
  filter( {case Some(y) => true; case None => false} ).
  map( _.get ).
  // ... more RDD operations with the good data

def getData(r: Result) = {
  val key = r.getRow
  var id = "(unk)"
  var x = -1L

  try {
    id = Bytes.toString(key, 0, 11)
    x = Long.MaxValue - Bytes.toLong(key, 11)
    // ... more code that might throw exceptions

    Some( ( id, ( List(x),
          // more stuff ...
        ) ) )
  } catch {
    case e: NullPointerException => {
      logWarning("Skipping id=" + id + ", x=" + x + "; \n" + e)
      None
    }
  }
}

是否有更为惯用的做法更短?在getData()和我正在做的map.filter.map舞蹈中,我觉得这看起来很混乱。

也许flatMap可以正常工作(在Seq中生成0或1个项目),但我不希望它在地图函数中展平我正在创建的元组,只是消除了空白

3 个答案:

答案 0 :(得分:7)

如果您更改getData以返回scala.util.Try,那么您可以大大简化转换。这样的事情可以奏效:

def getData(r: Result) = {
  val key = r.getRow
  var id = "(unk)"
  var x = -1L

  val tr = util.Try{
    id = Bytes.toString(key, 0, 11)
    x = Long.MaxValue - Bytes.toLong(key, 11)
    // ... more code that might throw exceptions

    ( id, ( List(x)
          // more stuff ...
     ) )
  } 

  tr.failed.foreach(e => logWarning("Skipping id=" + id + ", x=" + x + "; \n" + e))
  tr
}

然后你的变换可以这样开始:

myRDD.
  flatMap(tuple => getData(tuple._2).toOption)

如果您的TryFailure,它将通过None转变为toOption,然后作为flatMap逻辑的一部分删除。此时,转换中的下一步只会处理成功案例,即getData没有包装的基础类型(即无Option

答案 1 :(得分:7)

另一种常常被忽视的方法是使用collect(PartialFunction pf),这意味着“选择”或“收集”部分函数中定义的RDD中的特定元素。

代码如下所示:

val output = myRDD.collect{case Success(tuple) => tuple }

def getData(r: Result):Try[(String, List[X])] = Try {
        val id = Bytes.toString(key, 0, 11)
        val x = Long.MaxValue - Bytes.toLong(key, 11)
        (id, List(x))
}

答案 2 :(得分:1)

如果你可以删除数据,那么你可以使用mapPartitions。这是一个示例:

import scala.util._
val mixedData = sc.parallelize(List(1,2,3,4,0))
mixedData.mapPartitions(x=>{
  val foo = for(y <- x)
   yield {
    Try(1/y)
  }
  for{goodVals <- foo.partition(_.isSuccess)._1}
   yield goodVals.get
})

如果您想查看错误值,那么您可以使用accumulator或只使用日志。

您的代码看起来像这样:

val output = myRDD.
  mapPartitions( tupleIter => getCleanData(tupleIter) )
  // ... more RDD operations with the good data

def getCleanData(iter: Iter[???]) = {
  val triedData = getDataInTry(iter)
  for{goodVals <- triedData.partition(_.isSuccess)._1}
    yield goodVals.get
}

def getDataInTry(iter: Iter[???]) = {
  for(r <- iter) yield {
    Try{
      val key = r._2.getRow
      var id = "(unk)"
      var x = -1L
      id = Bytes.toString(key, 0, 11)
      x = Long.MaxValue - Bytes.toLong(key, 11)
      // ... more code that might throw exceptions
    }
  }
}