經過一些轉換后,我想使用 insertInto 將 spark 資料集保存到鑲木地板表中。
ds.write.mode(SaveMode.Overwrite).insertInto(tablename)
但是操作失敗,給我這個錯誤:
[TABLENAME] requires that the data to be inserted have the same number of columns as the target table: target table has 11 column(s) but the inserted data has 19 column(s)
正確的列數是 11,是我用來構建資料集的案例類中的屬性數,但是當我將其轉換為資料框并顯示列時,許多用于轉換的臨時列(來自 join 等的附加列) ...) 仍然存在,導致保存程序失敗。
我發現的解決方法是加載表資料并選擇其列:
val tableSchema = spark.table(tablename).schema
val dfWithCorrectColumns = ds.select(tableSchema.fieldNames.map(col) : _*)
但是這個解決方案似乎很笨拙。我知道saveAsTable將是具有模式強制機制的一個選項,但由于缺乏動態磁區覆寫,也不推薦這樣做。
有沒有一種簡單的方法可以將資料集“截斷”到其定義中,從而強制執行其架構?
uj5u.com熱心網友回復:
如果您使用案例類A 來創建ds型別的值,Dataset[A]那么您可以使用以下命令將其截斷為您需要的欄位:
val ds_clean: Dataset[A] = ds.map(identity)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/318736.html
下一篇:如何發送多條訊息作為我的來源
