Spark incremental loading overwrite old record

后端 未结 3 1356
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 07:39

I have a requirement to do the incremental loading to a table by using Spark (PySpark)

Here\'s the example:

Day 1

id | value
-----------
1  |         


        
3条回答
  •  我在风中等你
    2020-12-16 08:21

    Here you go! First Dataframe:

     >>> list1 = [(1, 'abc'),(2,'def')]
     >>> olddf = spark.createDataFrame(list1, ['id', 'value'])
     >>> olddf.show();
     +---+-----+
     | id|value|
     +---+-----+
     |  1|  abc|
     |  2|  def|
     +---+-----+
    

    Second Dataframe:

    >>> list2 = [(2, 'cde'),(3,'xyz')]
    >>> newdf = spark.createDataFrame(list2, ['id', 'value'])
    >>> newdf.show();
    +---+-----+
    | id|value|
    +---+-----+
    |  2|  cde|
    |  3|  xyz|
    +---+-----+
    

    Now join and merge these two datafame using full outer join and use coalesce function while select and can replace the null values wih user defined values.

    from pyspark.sql.functions import *
    
    >>> df = olddf.join(newdf, olddf.id == newdf.id,'full_outer').select(coalesce(olddf.id,newdf.id).alias("id"),coalesce(newdf.value,olddf.value).alias("value"))
    >>> df.show();
    +---+-----+
    | id|value|
    +---+-----+
    |  1|  abc|
    |  3|  xyz|
    |  2|  cde|
    +---+-----+
    

    I hope this should solve your problem. :-)

提交回复
热议问题