【问题标题】:How to make sure the correct column order while doing spark dataframe.write().insertInto("table")?如何在执行 spark dataframe.write().insertInto("table") 时确保正确的列顺序?
【发布时间】:2020-02-27 14:22:54
【问题描述】:

我正在使用以下代码将数据帧数据直接插入到 databricks 增量表中:

eventDataFrame.write.format("delta").mode("append").option("inferSchema","true").insertInto("some delta table"))

但如果创建 detla 表的列顺序与数据框列顺序不同,则值会混乱,然后不会写入正确的列。如何维护秩序?是否有执行此操作的标准方法/最佳实践?

【问题讨论】:

    标签: dataframe apache-spark databricks azure-databricks


    【解决方案1】:

    这很简单 -

    `

    ####in pyspark 
    
    df= spark.read.table("TARGET_TABLE")  ### table in which  we need to insert finally 
    
    df_increment ## the data frame which has random column order which we want to insert into TARGET_TABLE
    df_increment =df_increment.select(df.columns)
    df_increment.write.insertInto("TARGET_TABLE")
    

    `

    所以对你来说它会

    parent_df=   spark.read.table("some delta table") 
    eventDataFrame.select(parent_df.columns).write.format("delta").mode("append").option("inferSchema","true").insertInto("some delta table"))
    

    【讨论】:

      【解决方案2】:

      使用 saveAsTable 的列顺序无关紧要,spark 会根据列名找到正确的列位置。

      eventDataFrame.write.format("delta").mode("append").option("inferSchema","true").saveAsTable("foo")

      来自 spark 文档。

      DataFrame 的模式中的列顺序不需要与现有表的相同。与 insertInto 不同,saveAsTable 将使用列名来查找正确的列位置

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-06
        • 2019-05-24
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 2019-08-19
        相关资源
        最近更新 更多