【问题标题】:Get dataframe schema load to metadata table将数据框模式加载到元数据表
【发布时间】:2019-06-27 18:14:31
【问题描述】:

用例是读取文件并在其上创建数据框。之后获取该文件的架构并存储到数据库表中。

例如,我只是创建一个案例类并获取打印模式,但是我无法从中创建数据框

这是一个示例代码

case class Employee(Name:String, Age:Int, Designation:String, Salary:Int, ZipCode:Int)

val spark = SparkSession
.builder()
.appName("Spark SQL basic example")
.config("spark.master", "local")
.getOrCreate()

import spark.implicits._
val EmployeesData = Seq( Employee("Anto",   21, "Software Engineer", 2000, 56798))
val Employee_DataFrame = EmployeesData.toDF
val dfschema = Employee_DataFrame.schema

现在 dfschema 是一个结构类型,想把它转换成两列的数据框,如何实现

【问题讨论】:

  • dfschema 属于结构类型,具有案例类中定义的 5 列。你想转换成哪两列?

标签: scala apache-spark


【解决方案1】:

Spark >= 2.4.0

为了将架构保存为字符串格式,您可以使用StructTypetoDDL 方法。在您的情况下,DDL 格式应该是:

`Name` STRING, `Age` INT, `Designation` STRING, `Salary` INT, `ZipCode` INT

保存架构后,您可以从数据库中加载它并将其用作StructType.fromDDL(my_schema),这将返回一个 StructType 实例,您可以使用它来创建带有@Ajay 已经提到的spark.createDataFrame 的新数据框。

记住,您始终可以extract 给定案例类的架构:

import org.apache.spark.sql.catalyst.ScalaReflection
val empSchema = ScalaReflection.schemaFor[Employee].dataType.asInstanceOf[StructType]

然后您可以使用empSchema.toDDL 获取 DDL 表示。

火花

对于 Spark DataType.fromDDL 和 schema.simpleString。此外,您应该使用 DataType 实例,而不是返回 StructType,而忽略对 StructType 的强制转换:

val empSchema = ScalaReflection.schemaFor[Employee].dataType

empSchema.simpleString 的示例输出:

struct<Name:string,Age:int,Designation:string,Salary:int,ZipCode:int>

【讨论】:

  • 非常感谢,我注意到 spark 2.4 中引入的 DDL 方法的一件事
  • True Pratik,fromDDL 自 2.2.0 以来就存在。你用的是哪个版本?
  • 嗨,Pratik 我也修改了旧版本的答案
  • 欢迎您使用 Pratik,如果它对您有用,请告诉我
  • 工作就像一个魅力。你能告诉我类似的函数,比如 toDDL 或 python 也存在简单字符串吗?
【解决方案2】:

试试这个 -

//-- For local file
val rdd = spark.read.option("wholeFile", true).option("delimiter",",").csv(s"file:///file/path/file.csv").rdd

val schema = StructType(Seq(StructField("Name", StringType, true),
                            StructField("Age", IntegerType, true),
                            StructField("Designation", StringType, true),
                            StructField("Salary", IntegerType, true),
                            StructField("ZipCode", IntegerType, true)))

val df = spark.createDataFrame(rdd,schema)

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2018-04-07
    • 2023-03-06
    相关资源
    最近更新 更多