首页 > 解决方案 > 如何在没有 Only 的情况下生成 spark sql 截断查询

问题描述

我正在使用 Spark(3.0.0_preview)并从/向 GreenPlum(5.24 版)读取/写入。Greenplum 5.24 版不支持“truncate table only $table_name”命令。

使用 Spark 3.0.0_preview 和 jdbcdriver(org.postgresql" % "postgresql" % "42.2.5),Spark 生成的命令是“truncate table only $table_name”。

 df.write.format("jdbc").option("url", "jdbc:postgresql://test:5432/sample")
.option("user", "sample")
.option("password", "sample")
.option("dbtable", "test.employer")
.option("truncate", true) // **Genearte truncate table only**
.mode(SaveMode.Overwrite)
.save();

我想生成没有 ONLY 选项的截断命令。由于 Greenplum V5.24 不支持唯一的选项

标签: apache-sparkapache-spark-sqlgreenplum

解决方案


正如@mazaneicha 所提到的,Spark 的 PostgreSQL 方言只能生成 TRUNCATE ONLY

为了让这对我有用,我正在使用 Scala 截断我的表。不是一个好的修复,但在我们升级到只支持 TRUNCATE TABLE 的 GreenPlum 6 之前可以使用

 truncate(""test.employer", "jdbc:postgresql://test:5432/sample","sample","sample" )
 df.write.format("jdbc").option("url", "jdbc:postgresql://test:5432/sample")
 .option("user", "sample")
 .option("password", "sample")
 .option("dbtable", "test.employer")
 .mode(SaveMode.Append)
 .save();

 def truncate(tableName: String, jdbcUrl: String, username: String, password: 
 String) = {
 val connection = DriverManager.getConnection(jdbcUrl, username, password)
 connection.setAutoCommit(true)
 val statement = connection.createStatement()
 statement.execute(s"TRUNCATE TABLE $tableName")
 }

推荐阅读