[英]Pyspark - Dynamically create schema from json files
我在 Databricks 筆記本上使用 Spark 從 API 調用中提取一些數據。
我首先將 API 響應中的所有數據讀取到名為 df 的 dataframe 中。 但是,我只需要 API 響應中的幾列,而不是全部,還有
我將所需的列及其數據類型存儲在 json 文件中
{
"structure": [
{
"column_name": "column1",
"column_type": "StringType()"
},
{
"column_name": "column2",
"column_type": "IntegerType()"
},
{
"column_name": "column3",
"column_type": "DateType()"
},
{
"column_name": "column4",
"column_type": "StringType()"
}
]
}
然后我正在使用以下代碼構建架構
with open("/dbfs/mnt/datalake/Dims/shema_json","r") as read_handle:
file_contents = json.load(read_handle)
struct_fields = []
for column in file_contents.get("structure"):
struct_fields.append(f'StructField("{column.get("column_name")}",{column.get("column_type")},True)')
new_schema = StructType(struct_fields)
最后,我想使用此代碼創建一個 dataframe 具有正確數據類型的所需列
df_staging = spark.createDataFrame(df.rdd,schema = new_schema)
但是,當我這樣做時,我收到一條錯誤消息,說 'str' object has no attribute 'name'
要從 dataframe 獲取列的子集,您可以使用簡單的 select 與強制轉換相結合:
import importlib
cols=[f"cast({c['column_name']} as {getattr(importlib.import_module('pyspark.sql.types'), c['column_type'].replace('()',''))().simpleString()})" for c in file_contents['structure']]
df.selectExpr(*cols).show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.