[英]How to expire state of dropDuplicates in structured streaming to avoid OOM?
我想使用spark結構流來計算每天的唯一訪問權限,因此我使用以下代碼
.dropDuplicates("uuid")
並且在第二天應該放棄今天維持的狀態,以便我可以獲得第二天的唯一訪問權限並避免OOM。 spark文件表示使用帶水印的dropDuplicates,例如:
.withWatermark("timestamp", "1 day")
.dropDuplicates("uuid", "timestamp")
但必須在dropDuplicates中指定水印列。 在這種情況下,uuid和timestamp將被用作組合鍵,以使用相同的uuid和timestamp對元素進行重復數據刪除,這不是我所期望的。
那么有一個完美的解決方案嗎?
經過幾天的努力,我終於找到了自己的方式。
在研究水印和dropDuplicates的源代碼時,我發現除了eventTime列之外,水印還支持window列,因此我們可以使用以下代碼:
.select(
window($"timestamp", "1 day"),
$"timestamp",
$"uuid"
)
.withWatermark("window", "1 day")
.dropDuplicates("uuid", "window")
由於同一天的所有事件都具有相同的窗口,因此這將產生與僅使用uuid進行重復數據刪除相同的結果。 希望可以幫助某人。
以下是Spark文檔中提出的過程的修改。 訣竅是操縱事件時間,即將事件時間放入桶中。 假設事件時間以毫秒為單位。
// removes all duplicates that are in 15 minutes tumbling window.
// doesn't remove duplicates that are in different 15 minutes windows !!!!
public static Dataset<Row> removeDuplicates(Dataset<Row> df) {
// converts time in 15 minute buckets
// timestamp - (timestamp % (15 * 60))
Column bucketCol = functions.to_timestamp(
col("event_time").divide(1000).minus((col("event_time").divide(1000)).mod(15*60)));
df = df.withColumn("bucket", bucketCol);
String windowDuration = "15 minutes";
df = df.withWatermark("bucket", windowDuration)
.dropDuplicates("uuid", "bucket");
return df.drop("bucket");
}
我發現窗口功能不起作用所以我選擇使用window.start或window.end。
.select(
window($"timestamp", "1 day").start,
$"timestamp",
$"uuid"
)
.withWatermark("window", "1 day")
.dropDuplicates("uuid", "window")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.