I want to saving data into MySQL, overwrite the duplicate lines in some field and keep the data in MySQL that the pending data does not contain . I've tried the Mode.Overwrite/Mode.append that still can not satisfy my needs. So I try to loading the existing data from MySQL and find the lines. But while saving data into MySQL, the obtained DataFrame turns empty.
During the process, I've tried two methods:
- Find the data that does not exist in the pending data, then use UNION to joint the two parts. At last, use Mode.Overwrite to save.
- Find the data that does not exist in the pending data. Use the Mode.Overwrite to save the pending DataFrame and Mode.append to save the obtained DF.
Both methods are not available. The obtained DF always was empty while saving in Method 1 or after saving with Mode.OverWrite in method 2.
Codes are below:
var mysql_table = spark.sqlContext.read.format("jdbc").options(jdbc_options).load()
val list = pre_res.select("clientMacAddr").rdd.map(x => x.toString.substring(1,18)).collect()
val rec_diff = mysql_table.filter(x => !(list.contains(x.apply(0).toString)))
pre_res.write.mode("overwrite").format("jdbc").options(jdbc_options).save()
rec_diff.show()
rec_diff.write.mode("append").format("jdbc").options(jdbc_options).save()
The result is like this:
+------------------+----+
|clientMacAddr|var1|
+------------------+----+
+------------------+----+
Thanks.