假设我有以下名为customers 的数据集
lastVisit | id |
---|---|
2018-08-08 12:23:43.234 | 11 |
2021-12-08 14:13:45.4 | 12 |
@Xaleate,根据您的查询,似乎您想要实现的逻辑
current_date - lastVisits < x days
你试过使用spark中已有的datediff UDF吗?这是一个使用datediff的双线解决方案
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
object LastDateIssue {
val spark: SparkSession = SparkSession.builder().appName("Last Date issue").master("local[*]").getOrCreate()
def main(args: Array[String]): Unit = {
import spark.implicits._
//prepare customer data for test
var customers = Map(
"2018-08-08 12:23:43.234"-> 11,
"2021-12-08 14:13:45.4"-> 12,
"2022-02-01 14:13:45.4"-> 13)
.toSeq
.toDF("lastVisit", "id")
// number of days
val x: Int = 10
customers = customers.filter(datediff(lit(current_date()), col("lastVisit")) < x)
customers.show(20, truncate = false)
}
}
这将返回id=13,因为这是在过去10天内(您可以相应地选择x(
+---------------------+---+
|lastVisit |id |
+---------------------+---+
|2022-02-01 14:13:45.4|13 |
+---------------------+---+
使用date_sub函数。
df.filter($"lastVisit" > date_sub(current_date(),n)).show(false)