Apache Spark - 将csv数据加载到数据集的通用方法

时间:2018-03-13 15:59:37

标签: scala apache-spark apache-spark-sql spark-dataframe

我想用三个输入参数编写泛型方法:

  1. filePath - String
  2. 架构 - ?
  3. 案例类
  4. 所以,我的想法是编写一个这样的方法:

    def load_sms_ds(filePath: String, schemaInfo: ?, cc: ?) = {
      val ds = spark.read
        .format("csv")
        .option("header", "true")
        .schema(?)
        .option("delimiter",",")
        .option("dateFormat", "yyyy-MM-dd HH:mm:ss.SSS")
        .load(schemaInfo)
        .as[?]
    
       ds
    }
    

    并根据输入参数返回数据集。我不确定参数schemaInfo和cc应该是什么类型的?

1 个答案:

答案 0 :(得分:3)

首先,我会推荐阅读spark sql programming guide。这包含了一些我认为通常可以帮助你学习火花的东西。

让我们使用案例类来运行读取csv文件的过程来定义架构。

首先添加此示例所需的varioud导入:

import java.io.{File, PrintWriter} // for reading / writing the example data

import org.apache.spark.sql.types.{StringType, StructField} // to define the schema
import org.apache.spark.sql.catalyst.ScalaReflection // used to generate the schema from a case class

import scala.reflect.runtime.universe.TypeTag // used to provide type information of the case class at runtime
import org.apache.spark.sql.Dataset, SparkSession}
import org.apache.spark.sql.Encoder // Used by spark to generate the schema 

定义案例类,可以找到可用的不同类型here

case class Example(
    stringField : String,
    intField : Int,
    doubleField : Double
)

在给定案例类类型作为参数的情况下,添加用于提取模式(StructType)的方法:

// T : TypeTag means that an implicit value of type TypeTag[T] must be available at the method call site. Scala will automatically generate this for you. See [here][3] for further details. 
def schemaOf[T: TypeTag]: StructType = { 
    ScalaReflection
        .schemaFor[T] // this method requires a TypeTag for T
        .dataType
        .asInstanceOf[StructType] // cast it to a StructType, what spark requires as its Schema
}

定义一个从使用case类定义的模式的路径读入csv文件的方法:

// The implicit Encoder is needed by the `.at` method in order to create the Dataset[T]. The TypeTag is required by the schemaOf[T] call.
def readCSV[T : Encoder : TypeTag](
    filePath: String
)(implicit spark : SparkSession) : Dataset[T]= {
    spark.read
        .option("header", "true")
        .option("dateFormat", "yyyy-MM-dd HH:mm:ss.SSS")
        .schema(schemaOf[T])
        .csv(filePath) // spark provides this more explicit call to read from a csv file by default it uses comma and the separator but this can be changes.
        .as[T]
}

创建一个sparkSession:

implicit val spark = SparkSession.builder().master("local").getOrCreate()

将一些示例数据写入临时文件:

val data =
    s"""|stringField,intField,doubleField
        |hello,1,1.0
        |world,2,2.0
    |""".stripMargin
val file = File.createTempFile("test",".csv")
val pw = new PrintWriter(file)
pw.write(data)
pw.close()

调用此方法的示例:

import spark.implicits._ // so that an implicit Encoder gets pulled in for the case class
val df = readCSV[Example](file.getPath)
df.show()