【问题标题】:Facing "scala.MatchError: 1201 (of class java.lang.Integer)" while creating Data frame在创建数据框时面临“scala.MatchError: 1201 (of class java.lang.Integer)”
【发布时间】:2023-03-07 02:24:01
【问题描述】:

我正在执行以下代码以从文本文件创建数据框。

    import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.sql.{SQLContext, Row}
import org.apache.spark.sql.types.{StructType, StringType, StructField}


/**
  * Created by PSwain on 6/19/2016.
  */
object RddToDataframe extends App {

  val scnf=new SparkConf().setAppName("RddToDataFrame").setMaster("local[1]")
  val sc = new SparkContext(scnf)
  val sqlContext = new SQLContext(sc)

  val employeeRdd=sc.textFile("C:\\Users\\pswain\\IdeaProjects\\test1\\src\\main\\resources\\employee")

  //Creating schema

  val employeeSchemaString="id name age"
  val schema = StructType(employeeSchemaString.split(",").map( colNmae => StructField(colNmae,StringType,true)))

  //Creating  RowRdd
  val rowRdd= employeeRdd.map(row => row.split(",")).map(row => Row(row(0).trim.toInt,row(1),row(2).trim.toInt))

  //Creating dataframe = RDD[rowRdd] + schema
  val employeeDF=sqlContext.createDataFrame(rowRdd,schema). registerTempTable("Employee")

  sqlContext.sql("select * from Employee").show()


}

但在 InteliJ 中执行时,我发现类型不匹配错误如下。无法确定为什么会出现此错误,我只是将 string 转换为 integer 。员工文件有以下输入,它们都显示在一行中,但它们是一行。

1201,萨蒂什,25 1202,克里希纳,28 第1203章 39 1204, javed, 23 1205,普鲁德维,23

16/06/19 15:18:58 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
scala.MatchError: 1201 (of class java.lang.Integer)
    at org.apache.spark.sql.catalyst.CatalystTypeConverters$StringConverter$.toCatalystImpl(CatalystTypeConverters.scala:295)
    at org.apache.spark.sql.catalyst.CatalystTypeConverters$StringConverter$.toCatalystImpl(CatalystTypeConverters.scala:294)
    at org.apache.spark.sql.catalyst.CatalystTypeConverters$CatalystTypeConverter.toCatalyst(CatalystTypeConverters.scala:102)

【问题讨论】:

  • 如果字符串用空格分隔"id name age",为什么要将employeeSchemaString.split(","), 分开?

标签: scala apache-spark spark-dataframe


【解决方案1】:

创建架构时,所有列类型都定义为 StringType。

val schema = StructType(employeeSchemaString.split(",").map( colNmae => StructField(colNmae,StringType,true)))

但是 rowRDD 有 int、string 和 int 类型的列。

这是工作代码

val structType= {
    val id = StructField("id", IntegerType)
    val name = StructField("name", StringType)
    val age = StructField("age", IntegerType)
    new StructType(Array(id, name , age))
}

val rowRdd= employeeRdd.map(row => row.split(",")).map(row => Row(row(0).trim().toInt,row(1),row(2).trim().toInt))

sqlContext.createDataFrame(rowRdd,structType). registerTempTable("Employee")

sqlContext.sql("select * from Employee").show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2019-04-26
    • 1970-01-01
    • 2018-03-05
    相关资源
    最近更新 更多