The idea is to identify users who bought an item offline (no in the online column) and tried to buy the same item online (yes in the online column) in the last 7 days.
This means that for each no in the online column I need to search through the yes values 7 days prior, which also match the user_ID and item values of the no instance and then label matches as 1 and non-matches as 0.
Sample dataset (notes on the right):
+-------+----+------+--------------+
|user_ID|item|online| datetime|
+-------+----+------+--------------+
| 1| 66| yes| 02-10-21 9:30|
| 1| 24| yes| 02-10-21 9:30|
| 1| 66| no| 06-10-21 9:30| # <- 1 ('user_ID' and 'item' matched in the last 7 days)
| 2| 24| no| 03-10-21 8:01| # <- 0 ('user_ID' didnt match in the last 7 days)
| 2| 24| yes| 03-10-21 8:02|
| 2| 24| no| 03-10-21 8:03| # <- 1 ('user_ID' and 'item' matched in the last 7 days)
| 3| 31| yes| 05-10-21 8:32|
| 3| 66| yes|10-10-21 10:57|
| 3| 66| no|14-10-21 12:07| # <- 1 ('user_ID' and 'item' matched in the last 7 days)
| 3| 31| no|15-10-21 12:07| # <- 0 ('item' didnt match in the last 7 days)
+-------+----+------+--------------+
Resulting dataset:
+-------+----+------+--------------+------+
|user_ID|item|online| datetime|result|
+-------+----+------+--------------+------+
| 1| 66| no| 06-10-21 9:30| 1|
| 2| 24| no| 03-10-21 8:01| 0|
| 2| 24| no| 03-10-21 8:03| 1|
| 3| 66| no|14-10-21 12:07| 1|
| 3| 31| no|15-10-21 12:07| 0|
+-------+----+------+--------------+------+
Can't figure this one out. Is there a way of doing this with a windowed function? I'm working with spark and a large dataset (>10 mln records).
Any pyspark or sql magicians that could help?