如何解决将数据集[Dataset [Column]]展平为数据集[Column]
我正在尝试捕获数据库所有表的元数据。我正在使用spark.catalog
api提取元数据。我写了以下方法
def getColumns(tables:Dataset[Table]): Dataset[Column] = {
tables.map(table => spark.catalog.listColumns(table.name))
}
此方法返回Dataset[Dataset[Colums]]
。我如何将其转换为Dataset[Column]
,以便可以将其另存为表格?请建议是否还有其他有效的方法来捕获表的所有元数据。
解决方法
// 1. only column name
val c1 = spark.catalog.listColumns("database-name.table-name").select('name)
// c1: org.apache.spark.sql.DataFrame = [name: string]
c1.printSchema
// root
// |-- name: string (nullable = true)
// 2. Full info
val c1 = spark.catalog.listColumns("database-name.table-name")
// c1: org.apache.spark.sql.Dataset[org.apache.spark.sql.catalog.Column] = [name:
string,description: string ... 4 more fields]
c1.printSchema
// root
// |-- name: string (nullable = true)
// |-- description: string (nullable = true)
// |-- dataType: string (nullable = true)
// |-- nullable: boolean (nullable = false)
// |-- isPartition: boolean (nullable = false)
// |-- isBucket: boolean (nullable = false)
// 3. All info about columns in tables database
import org.apache.spark.sql.functions._
val dbName = "set database name"
val listTables = spark.catalog.listTables(dbName)
.select('name).as[String]
.collect().toList
val listDF = listTables.map(t => {
val colsDF = spark.catalog.listColumns(dbName,t)
.withColumn("namneTable",lit(t))
.withColumn("dbName",lit(dbName))
colsDF
})
val resDF = listDF.reduce(_ union _)
resDF.printSchema
// root
// |-- name: string (nullable = true)
// |-- description: string (nullable = true)
// |-- dataType: string (nullable = true)
// |-- nullable: boolean (nullable = false)
// |-- isPartition: boolean (nullable = false)
// |-- isBucket: boolean (nullable = false)
// |-- namneTable: string (nullable = false)
// |-- dbName: string (nullable = false)
resDF.write.format("parquet").saveAsTable(.....)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。