我需要从 Spark DataFrame 向 MySQL 写入大约 100 万行,但插入速度太慢。我该如何改进它?
代码如下:
df = sqlContext.createDataFrame(rdd, schema)
df.write.jdbc(url='xx', table='xx', mode='overwrite')
https://stackoverflow.com/a/10617768/3318517中的答案对我有用。将
rewriteBatchedStatements=true
添加到连接 URL。 (请参阅连接器/J 的配置属性。)
我的基准测试从 3325 秒变为 42 秒!
myDf.write
.format("jdbc")
.mode(SaveMode.Append)
.option("driver", "com.mysql.jdbc.Driver")
.option("url", s"jdbc:mysql://${targetHost}/${targetDB}")
.option("user", targetUser)
.option("password", targetPassword)
.option("dbtable", targetTable)
.option("rewriteBatchedStatements", "true")
.option("autoReconnect", "true")
.option("numPartitions", "8")
.option("batchsize", "10000")
.option("compression", "snappy")
.save()
为什么我的代码仍然很慢。