另一种方法是使用 StructType.. sql、simpleString、TreeString 等可用的方法...
您可以从 Dataframe 的架构创建 DDL,可以从您的 DDL 创建 Dataframe 的架构 ..
这是一个例子 - (Till Spark 2.3)
// Setup Sample Test Table to create Dataframe from
spark.sql(""" drop database hive_test cascade""")
spark.sql(""" create database hive_test""")
spark.sql("use hive_test")
spark.sql("""CREATE TABLE hive_test.department(
department_id int ,
department_name string
)
""")
spark.sql("""
INSERT INTO hive_test.department values ("101","Oncology")
""")
spark.sql("SELECT * FROM hive_test.department").show()
/***************************************************************/
现在我可以使用 Dataframe。在实际情况下,您将使用 Dataframe Readers 从文件/数据库创建数据框。让我们使用它的模式来创建 DDL
// Create DDL from Spark Dataframe Schema using simpleString function
// Regex to remove unwanted characters
val sqlrgx = """(struct<)|(>)|(:)""".r
// Create DDL sql string and remove unwanted characters
val sqlString = sqlrgx.replaceAllIn(spark.table("hive_test.department").schema.simpleString, " ")
// Create Table with sqlString
spark.sql(s"create table hive_test.department2( $sqlString )")
从 Spark 2.4 开始,您可以在 StructType 上使用 fromDDL 和 toDDL 方法 -
val fddl = """
department_id int ,
department_name string,
business_unit string
"""
// Easily create StructType from DDL String using fromDDL
val schema3: StructType = org.apache.spark.sql.types.StructType.fromDDL(fddl)
// Create DDL String from StructType using toDDL
val tddl = schema3.toDDL
spark.sql(s"drop table if exists hive_test.department2 purge")
// Create Table using string tddl
spark.sql(s"""create table hive_test.department2 ( $tddl )""")
// Test by inserting sample rows and selecting
spark.sql("""
INSERT INTO hive_test.department2 values ("101","Oncology","MDACC Texas")
""")
spark.table("hive_test.department2").show()
spark.sql(s"drop table hive_test.department2")