2017-07-15 120 views
0

我怎樣做異常處理的星火 - 斯卡拉無效記錄 這裏是我的代碼:如果輸入的數據是好的Apache的火花Scala的異常處理

val rawData = sc.textFile(file) 
val rowRDD = rawData.map(line => Row.fromSeq(line.split(","))) 
val rowRDMapped = rowRDD.map { x => x.get(1), x.get(10) } 
val DF = rowRDMapped.toDF("ID", "name") 

一切工作正常,如果我沒有足夠的字段,我得到ArrayIndexOutOfBoundException。

我試圖把的try-catch左右,但我不能跳過無效數據的記錄,通過嘗試捕捉

val rowRDMapped = rowRDD.map { try { 
            x => x.get(1), x.get(10) 
            }catch { 
             println("Invalid Data") 
             //Here it expects to return ROW, but I am not sure what to do here, since I dont want any data to be returned. 
            } 
          } 

請讓我知道如何解決與嘗試捕捉的問題,如果有任何更好的解決方案,這也將幫助很多

+0

你想要什麼?跳過太短的行嗎? – Zernike

+0

@ Zernike,感謝您的期待,是的,我需要跳過短行,這會導致索引超出限制的異常。 – user3124284

回答

1

最簡單的:

val rawData = sc.textFile(file) 
val rowRDD = rawData.map(line => Row.fromSeq(line.split(","))) 
val rowRDMapped = rowRDD.filter(_.length >= 11).map(x => x.get(1), x.get(10)) 

更好地使用collect(不other function混淆)

val rowRDMapped = rowRDD.collect{x if x.length >= 11 => x.get(1), x.get(10)} 
+0

'> = 9'應該足夠好,不是嗎? –

+0

無關緊要。真正的要求可能是任何。對於這個例子,正確的是'11',因爲Row有從零開始的索引。 – Zernike

+0

是的你是對的。我也要寫11,但我只是錯誤地寫了9 –

1

您可以使用嘗試捕捉儘可能下面,後來

val rawData = sc.textFile(file) 
val rowRDD = rawData.map(line => Row.fromSeq(line.split(","))) 
val rowRDMapped = rowRDD.map(x => (Try(x.get(1).toString) getOrElse "blank", Try(x.get(10).toString) getOrElse "blank")) 
val DF = rowRDMapped.toDF("ID", "name").filter($"name" =!= "blank") 
1

相反的try-catch的過濾器,你可以使用下面Try

代碼會過濾掉數據線,沒有足夠的字段,並獲得剩餘的數據幀。

val rawData = sc.textFile(line) 
val rowRDD = rawData.map(line => Row.fromSeq(line.split(","))) 
val rowRDMapped = rowRDD.flatMap{ x => Try(x.getString(1), x.getString(10)).toOption } 
val DF = rowRDMapped.toDF("ID", "name")