我正在映射一个 HBase 表,每个 HBase 行生成一个 RDD 元素。但是,有时该行有错误的数据(在解析代码中抛出 NullPointerException),在这种情况下我只想跳过它。
我让我的初始映射器返回 anOption
以指示它返回 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
也许 aflatMap
可以工作(在 a 中生成 0 或 1 个项目Seq
),但我不希望它使我在 map 函数中创建的元组变平,只是消除空。