Let's suppose to have this Pyspark dataframe:
x = np.random.randint(1, 100, 1000)
y = np.random.randint(1, 100, 1000)
z = np.random.randint(1, 100, 1000)
df = pd.DataFrame({'x': x, 'y': y, 'z': z})
spark_df = spark.createDataFrame(df)
Let's suppose to have this list of values:
lst = [10, 20, 30]
I would like to retrieve all the 3 (=len(lst)) rows of spark_df such that the difference between each value of lst and spark_df.x is the lowest. I would like to retrieve this three values as a spark dataframe. E.g:
+---+---+---+
| x| y| z|
+---+---+---+
| 11| 32| 84|
| 22| 12| 38|
| 29| 14| 12|
+---+---+---+
In this case:
11is the closestspark_df.xvalue to1022is the closestspark_df.xvalue to2029is the closestspark_df.xvalue to30
How can achieve this result in Pyspark 3+?
Note: this is only a toy example and the list of values could be in the order of thousands.