错误意味着您不能在 UDF 中使用 Spark 数据帧。但是由于您包含数据库和表名称的数据框很可能很小,因此只需使用 Python for 循环就足够了,以下是一些可能有助于获取数据的方法:
from pyspark.sql import Row
# assume dfs is the df containing database names and table names
dfs.printSchema()
root
|-- database: string (nullable = true)
|-- tableName: string (nullable = true)
方法一:使用 df.dtypes
运行 sql select * from database.tableName limit 1 生成 df 并返回其 dtypes,将其转换为 StringType()。
data = []
DRow = Row('database', 'tableName', 'dtypes')
for row in dfs.collect():
try:
dtypes = spark.sql('select * from `{}`.`{}` limit 1'.format(row.database, row.tableName)).dtypes
data.append(DRow(row.database, row.tableName, str(dtypes)))
except Exception, e:
print("ERROR from {}.{}: [{}]".format(row.database, row.tableName, e))
pass
df_dtypes = spark.createDataFrame(data)
# DataFrame[database: string, tableName: string, dtypes: string]
注意:
-
使用dtypes 而不是str(dtypes) 将得到以下架构,其中_1 和_2 分别是col_name 和col_dtype:
root
|-- database: string (nullable = true)
|-- tableName: string (nullable = true)
|-- dtypes: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- _1: string (nullable = true)
| | |-- _2: string (nullable = true)
使用此方法,每个表将只有一行。对于接下来的两种方法,表的每个 col_type 都有自己的行。
方法二:使用描述
您还可以通过运行spark.sql("describe tableName") 直接获取数据帧来检索此信息,然后使用reduce 函数将所有表的结果合并。
from functools import reduce
def get_df_dtypes(db, tb):
try:
return spark.sql('desc `{}`.`{}`'.format(db, tb)) \
.selectExpr(
'"{}" as `database`'.format(db)
, '"{}" as `tableName`'.format(tb)
, 'col_name'
, 'data_type')
except Exception, e:
print("ERROR from {}.{}: [{}]".format(db, tb, e))
pass
# an example table:
get_df_dtypes('default', 'tbl_df1').show()
+--------+---------+--------+--------------------+
|database|tableName|col_name| data_type|
+--------+---------+--------+--------------------+
| default| tbl_df1| array_b|array<struct<a:st...|
| default| tbl_df1| array_d| array<string>|
| default| tbl_df1|struct_c|struct<a:double,b...|
+--------+---------+--------+--------------------+
# use reduce function to union all tables into one df
df_dtypes = reduce(lambda d1, d2: d1.union(d2), [ get_df_dtypes(row.database, row.tableName) for row in dfs.collect() ])
方法三:使用 spark.catalog.listColumns()
使用 spark.catalog.listColumns() 创建 collections.Column 对象列表,检索 name 和 dataType 并合并数据。生成的数据框在它们自己的列上使用 col_name 和 col_dtype 进行规范化(与使用 Method-2 相同)。
data = []
DRow = Row('database', 'tableName', 'col_name', 'col_dtype')
for row in dfs.select('database', 'tableName').collect():
try:
for col in spark.catalog.listColumns(row.tableName, row.database):
data.append(DRow(row.database, row.tableName, col.name, col.dataType))
except Exception, e:
print("ERROR from {}.{}: [{}]".format(row.database, row.tableName, e))
pass
df_dtypes = spark.createDataFrame(data)
# DataFrame[database: string, tableName: string, col_name: string, col_dtype: string]
注意:不同的 Spark 发行版/版本在检索元数据时可能与 describe tbl_name 和其他命令的结果不同,请确保在查询中使用正确的列名。