我正在尝试通过很少的转换(添加日期)将 json 文件转换为镶木地板,但是我需要先对这些数据进行分区,然后再将其保存到镶木地板。
我在这个区域撞墙了。
下面是表的创建过程:
df_temp = spark.read.json(data_location) \
.filter(
cond3
)
df_temp = df_temp.withColumn("date", fn.to_date(fn.lit(today.strftime("%Y-%m-%d"))))
df_temp.createOrReplaceTempView("{}_tmp".format("duration_small"))
spark.sql("CREATE TABLE IF NOT EXISTS {1} LIKE {0}_tmp LOCATION '{2}/{1}'".format("duration_small","duration", warehouse_location))
spark.sql("DESC {}".format("duration"))
然后关于转换的保存:
df_final.write.mode("append").format("parquet").partitionBy("customer_id", "date").saveAsTable('duration')
但这会产生以下错误:
pyspark.sql.utils.AnalysisException: '\n指定的分区与现有表 default.duration 的分区不匹配。\n指定的分区列:[customer_id, date]\n现有的分区列:[]\n ;'
架构是:
root
|-- action_id: string (nullable = true)
|-- customer_id: string (nullable = true)
|-- duration: long (nullable = true)
|-- initial_value: string (nullable = true)
|-- item_class: string (nullable = true)
|-- set_value: string (nullable = true)
|-- start_time: string (nullable = true)
|-- stop_time: string (nullable = true)
|-- undo_event: string (nullable = true)
|-- year: integer (nullable = true)
|-- month: integer (nullable = true)
|-- day: integer (nullable = true)
|-- date: date (nullable = true)
因此,我尝试将创建表更改为:
spark.sql("CREATE TABLE IF NOT EXISTS {1} LIKE {0}_tmp PARTITIONED BY (customer_id, date) LOCATION '{2}/{1}'".format("duration_small","duration", warehouse_location))
但这会产生如下错误:
...不匹配的输入 'PARTITIONED' 期望 ...
所以我发现 PARTITIONED BY 不起作用,LIKE但我的想法已经用完了。如果使用USING而不是LIKE我得到错误:
pyspark.sql.utils.AnalysisException: '当未定义表架构时,不允许指定分区列。当未提供表架构时,将推断架构和分区列。;'
创建表时我应该如何添加分区?
Ps - 一旦使用分区定义了表的架构,我想简单地使用:
df_final.write.format("parquet").insertInto('duration')