如何使用 spark-scala 将 Dataframe 的模式作为字符串获取?

How to get the schema of the Dataframe as a string using spark-scala?

我是数据帧的新手,我的问题是有什么方法可以在 spark scala 中将数据帧模式作为字符串获取?

val df = spark.read.option("inferSchema","true").option("header","true").csv("sample_file1.txt")
df.show(truncate = false)

我已经阅读了上面的数据框,在结果部分我得到的架构为:

Schema: code0, code1, date, hi, _c4, first_name, _c6, last_name1, _c8, _c9, _c10, _c11, _c12, _c13, _c14, _c15, _
c16, _c17, _c18, _c19, _c20, _c21, _c22, _c23, _c24

我如何才能将其作为字符串读取,因为我需要通过将其作为字符串传递来在 spark SQL 中验证此模式..

请分享您的建议。

示例数据帧的生成

val df = spark.range(1).selectExpr("'hello' as mystr","1 as myint","2.3 as mydec","current_date as mydt")

解决方案

val cols = df.columns.mkString(",")

println(cols)

mystr,myint,mydec,mydt

如果您希望将列列表作为字符串,David 的回答可以。如果您希望将实际模式作为字符串(出于某种原因):

val schemaAsString = yourDF.schema.toString