I've been trying to update a series of JSON blobs via Pyspark, SparkSQL, and Pandas but have been unsuccessful. Here is what the data looks like:
#+---+---------+------------------------------------------+
#|ID |Timestamp|Properties |
#+---+---------+------------------------------------------+
#|a |7 |{"a1": 5, "a2": 8} |
#|b |12 |{"b1": 36, "b2": "u", "b3": 17, "b8": "c"}|
#|a |8 |{"a2": 4} |
#|a |10 |{"a3": "z", "a4": "t"} |
#|a |5 |{"a1": 3, "a2": 12, "a4": "r"} |
#|b |20 |{"b2": "k", "b3": 9} |
#|b |14 |{"b8": "y", "b3": 2} |
#+---+---------+------------------------------------------+
I want a query that will partition the rows by the ID field and sort it by the Timestamp field. After this the Properties field would cumulatively get merged in each partition to create a new column New Props. So the output would be this:
#+---+---------+------------------------------------------+------------------------------------------+------+
#|ID |Timestamp|Properties |New_Props |rownum|
#+---+---------+------------------------------------------+------------------------------------------+------+
#|a |5 |{"a1": 3, "a2": 12, "a4": "r"} |{"a1": 3, "a2": 12, "a4": "r"} |1 |
#|a |7 |{"a1": 5, "a2": 8} |{"a1": 5, "a2": 8, "a4": "r"} |2 |
#|a |8 |{"a2": 4} |{"a1": 5, "a2": 4, "a4": "r"} |3 |
#|a |10 |{"a3": "z", "a4": "t"} |{"a1": 5, "a2": 4, "a3": "z", "a4": "t"} |4 |
#|b |12 |{"b1": 36, "b2": "u", "b3": 17, "b8": "c"}|{"b1": 36, "b2": "u", "b3": 17, "b8": "c"}|1 |
#|b |14 |{"b8": "y", "b3": 2} |{"b1": 36, "b2": "u", "b3": 2, "b8": "y"} |2 |
#|b |20 |{"b2": "k", "b3": 9} |{"b1": 36, "b2": "k", "b3": 9, "b8": "y"} |3 |
#+---+---------+------------------------------------------+------+------------------------------------------+
Formula: Starting from rownum 2, get the New Props column value of the previous row (rownum 1) and update it with the value in column Properties of the current row (rownum 2).
I tried using the LAG function but I can't use a column that I'm currently calculating within the function itself.
To create the Next Props column I tried this CASE statement but it did not work:
CASE
WHEN rownum != 1 THEN concat(properties, LAG(next_props, 1) OVER (PARTITION BY contentid ORDER BY updateddatetime))
ELSE next_props
END AS new_props
I've been trying different things for awhile but I'm stuck. I can probably do it with a for loop and the python dict.update() function but I'm worried about efficiency. Any help is appreciated.