如何在收到记录的年份,月份和日期将流写入S3?

时间:2017-11-10 17:37:11

标签: scala apache-spark spark-structured-streaming

我有一个简单的流,可以从Kafka主题中读取一些数据:

 val ds = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "host1:port1")
      .option("subscribe", "topic1")
      .option("startingOffsets", "earliest")
      .load()

val df = ds.selectExpr("cast (value as string) as json")
      .select(from_json($"json", schema).as("data"))
      .select("data.*")

我想根据收到的日期将这些数据存储在S3中,例如:

s3_bucket/year/month/day/data.json

当我想写数据时:

df.writeStream
  .format("json")
  .outputMode("append")
  .option("path", s3_path)
  .start()

但如果我这样做,我只能指定一条路径。有没有办法根据日期动态更改s3路径?

1 个答案:

答案 0 :(得分:2)

使用partitionBy子句:

import org.apache.spark.sql.functions._

df.select(
    dayofmonth(current_date()) as "day",
    month(current_date()) as "month",
    year(current_date()) as "year",
    $"*")
  .writeStream
  .partitionBy("year", "month", "day")
  ... // all other options