Scala 获取java.lang.ArrayIndexOutOfBoundsException:应用聚合函数时spark中的1

Scala 获取java.lang.ArrayIndexOutOfBoundsException:应用聚合函数时spark中的1,scala,apache,apache-spark,indexoutofboundsexception,Scala,Apache,Apache Spark,Indexoutofboundsexception,我正在尝试对数据集进行一些转换。在执行df.show()操作时读取数据集后,我将获得spark shell中列出的行。但是当我尝试执行df.count或任何聚合函数时,我得到了 java.lang.ArrayIndexOutOfBoundsException:1 如果文本文件包含一些空行或拆分后的字段数不是13,则函数stringToPost()可能会导致Java错误ArrayIndexOutOfBoundsException 由于Spark的惰性计算,只有在执行类似于count的操作时才会注意

我正在尝试对数据集进行一些转换。在执行
df.show()
操作时读取数据集后,我将获得spark shell中列出的行。但是当我尝试执行
df.count
或任何聚合函数时,我得到了

java.lang.ArrayIndexOutOfBoundsException:1


如果文本文件包含一些空行或拆分后的字段数不是13,则函数
stringToPost()
可能会导致Java错误
ArrayIndexOutOfBoundsException


由于Spark的惰性计算,只有在执行类似于
count

的操作时才会注意到此类错误。如果文本文件包含一些空行或拆分后的字段数不是13,则函数
stringToPost()
可能会导致Java错误
ArrayIndexOutOfBoundsException


由于Spark的惰性评估,只有在执行类似于
count

的操作时,您才会注意到此类错误,您将使用
选项
类型声明
案例类中的所有变量,但在map函数中,只需基于该代码创建
post
类,而不创建
部分(r(0))
,如果您的源文件有任何空行,您将看到该错误。您在
case class
中使用
选项
类型声明了所有变量,但在map函数中仅创建
post
类而不使用
部分(r(0))
时,如果您的源文件有任何空行,您将看到该错误。
val itpostsrow = sc.textFile("/home/jayk/Downloads/spark-data")

import scala.util.control.Exception.catching    
import java.sql.Timestamp

implicit class StringImprovements(val s:String) {
      def toIntSafe = catching(classOf[NumberFormatException]) 
 opt    s.toInt
      def toLongsafe = catching(classOf[NumberFormatException]) 
 opt s.toLong
      def toTimeStampsafe = catching(classOf[IllegalArgumentException])       opt Timestamp.valueOf(s)
      }

case class Post(commentcount:Option[Int],lastactivitydate:Option[java.sql.Timestamp],ownerUserId:Option[Long],body:String,score:Option[Int],creattiondate:Option[java.sql.Timestamp],viewcount:Option[Int],title:String,tags:String,answerCount:Option[Int],acceptedanswerid:Option[Long],posttypeid:Option[Long],id:Long)

def stringToPost(row:String):Post = {
      val r = row.split("~")

      Post(r(0).toIntSafe,
           r(1).toTimeStampsafe,
           r(2).toLongsafe,
           r(3),
           r(4).toIntSafe,
           r(5).toTimeStampsafe,
           r(6).toIntSafe,
           r(7),
           r(8),
           r(9).toIntSafe,
           r(10).toLongsafe,
           r(11).toLongsafe,
           r(12).toLong)
   }
   
val itpostsDFcase1 = itpostsrow.map{x=>stringToPost(x)}
val itpostsDF = itpostsDFcase1.toDF()