【问题标题】:How do I insert data in selective columns using PySpark?如何使用 PySpark 在选择性列中插入数据?
【发布时间】:2021-11-13 12:07:43
【问题描述】:

我在 Redshift 上有一个表,我想使用 pyspark 数据框向其中插入一些数据。
redshift 表有架构:

CREATE TABLE admin.audit_of_all_tables
(
    wh_table_name varchar,
    wh_schema_name varchar,
    wh_population_method integer,
    wh_audit_date timestamp without time,
    wh_percent_change numeric(15,5),
    wh_s3_path varchar
)
DISTSTYLE AUTO;

在我的数据框中,我只想保留前 4 列的值并将该数据框的数据写入此表。
我的数据框是这样的:

现在,我想在 Redshift 上对我的表执行 df.write.format,但我需要以某种方式指定我只想将数据插入前四列并且不为最后两列传递任何值(保持它们为空默认)。
知道如何使用dataframe.write.format(或任何方法)来指定它。
感谢阅读。

【问题讨论】:

    标签: python dataframe pyspark apache-spark-sql amazon-redshift


    【解决方案1】:

    您可以使用selectExpr 选择前四列以及带有null 的另外两列,它们已经cast 成为所需类型:

    df2 = df.selectExpr("table_name as wh_table_name",
        "schema_name as wh_schema_name",
        "population_method as wh_population_method",
        "audit_date as wh_audit_date",
        "cast(null as double) as wh_percent_change",
        "cast(null as string) as wh_s3_path")
    
    df2.write....
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2011-08-04
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多