使用pyspark更新MySQL表

时间:2018-06-05 09:46:36

标签: mysql apache-spark pyspark mysql-python pyspark-sql

我知道不可能只使用Spark更新MySQL表,但是我尝试了一些东西来避免它,但它不起作用。

假设我有一个表last_modification,我将用户名保存为id,即具有不同服务的系统的最后修改日期。每次我处理一些数据时,我必须更新该用户的数据被修改的日期,如果新用户进入系统,我必须将其插入表中。

过程是:

  1. 从SQL表中读取数据:

    df_last_mod = sqlContext.read.jdbc(url=url, table="last_modification", properties=properties)
    
  2. 从该DataFrame中提取将要处理的用户(last_mod_actual)并将其余用户保留在RDD(last_mod_aux)中:

    last_mod_actual = (df_last_mod
                   .rdd
                   .filter(lambda x: x[0] == service)
                   )
    
  3. 从已处理用户(现名为last_mod_rdd)的RDD更新修改日期,并将其加入未修改用户的RDD:

    union_rdd = last_mod_rdd.union(last_mod_aux)
    
  4. 这部分是额外的,以避免丢失数据,但不知道是否可以忽略它。在这里,我创建一个临时表并缓存它:

    header = (sqlContext
               .createDataFrame(union_rdd,header_schema)
               .createOrReplaceTempView("union_header")
               )
    sqlContext.cacheTable("union_header")
    
  5. 最后我使用JDBC编写表:

    dd = sqlContext.table("union_header")`
    
    dd.write.format('jdbc').options(
           url= url,
           driver="com.mysql.jdbc.Driver",
           dbtable="last_modification",
           user=user,
           password=password).mode('overwrite').save()
    
  6. 此代码似乎有效,但其他代码只保存修改后的用户并删除未修改的用户。在写入SQL表之前插入dd.show()时,程序看起来效果更好,但实际上并不知道为什么,它会随机工作。

0 个答案:

没有答案