I want to implement the following things
For example I have Emp file's (2 files)
i want to select only 2 columns for example Empid and EmpName if file doesn't have EmpName it should select one column of Empid dataframe
1) Emp1.csv (File)
Empid EmpName Dept
1 ABC IS
2 XYZ COE
2) Emp.csv (File)
Empid EmpName
1 ABC
2 XYZ
Code tried up till now
scala> val SourceData = spark.read.format("com.databricks.spark.csv").option("inferSchema", "true").option("delimiter", ",").option("header", "true").load("/root/Empfiles/")
SourceData: org.apache.spark.sql.DataFrame = [Empid: string, EmpName: string ... 1 more field]
scala> SourceData.printSchema
root
|-- Empid: string (nullable = true)
|-- EmpName: string (nullable = true)
|-- Dept: string (nullable = true)
This code works if specify all column names of file
scala> var FormatedColumn = SourceData.select(
| SourceData.columns.map {
| case "Empid" => SourceData("Empid").cast(IntegerType).as("empid")
| case "EmpName" => SourceData("EmpName").cast(StringType).as("empname")
| case "Dept" => SourceData("Dept").cast(StringType).as("dept")
| }: _*
| )
FormatedColumn: org.apache.spark.sql.DataFrame = [empid: int, empname: string ... 1 more field]
But i want only specific 2 columns it fails (if column is available it show select and change the datatype and column name)
scala> var FormatedColumn = SourceData.select(
| SourceData.columns.map {
| case "Empid" => SourceData("Empid").cast(IntegerType).as("empid")
| case "EmpName" => SourceData("EmpName").cast(StringType).as("empname")
| }: _*
| )
scala.MatchError: Dept (of class java.lang.String)
at $anonfun$1.apply(<console>:32)
at $anonfun$1.apply(<console>:32)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
... 53 elided