【问题标题】:how to force avro writer to write timestamp in UTC in spark scala dataframe [duplicate]如何强制avro writer在spark scala数据帧中以UTC格式写入时间戳[重复]
【发布时间】:2020-05-23 18:46:57
【问题描述】:

我需要将 Timestamp 字段写入 avro 并确保数据以 UTC 格式保存。当前 avro 将其转换为服务器本地时区中的 long (timestamp millis ),这会导致问题,就好像服务器读取 bk 是不同的时区一样。我查看了 DataFrameWriter,它似乎提到了一个名为 timeZone 的选项,但它似乎没有帮助。有没有办法强制 Avro 考虑在特定时区收到的所有时间戳字段?

**CODE SNIPPET** 
--write to spark avro

val data = Seq(Row("1",java.sql.Timestamp.valueOf("2020-05-11 15:17:57.188")))
val schemaOrig = List( StructField("rowkey",StringType,true)
,StructField("txn_ts",TimestampType,true))
val sourceDf =  spark.createDataFrame(spark.sparkContext.parallelize(data),StructType(schemaOrig))
sourceDf.write.option("timeZone","UTC").avro("/test4")

--now try to read back from avro
spark.read.avro("/test4").show(false)
avroDf.show(false)

original value in soure 2020-05-11 15:17:57.188
in avro  1589224677188
read bk from avro wt out format 
+-------------+-------------+
|rowkey       |txn_ts       |
+-------------+-------------+
|1            |1589224677188|
+-------------+-------------+

This is mapping fine but issue is if the local time of the server writing is EST and the one reading back is GMT it would give problem . 

println(new java.sql.Timestamp(1589224677188L))
2020-05-11 7:17:57.188   -- time in GMT

【问题讨论】:

    标签: apache-spark apache-spark-sql avro spark-avro


    【解决方案1】:

    .option("timeZone","UTC") 选项不会将时间戳转换为 UTC 时区。

    设置此 spark.conf.set("spark.sql.session.timeZone", "UTC") 配置属性以将 UTC 设置为所有时间戳的默认时区。

    spark.sql.session.timeZone 属性的默认值为 JVM 系统本地时区(如果未设置)。

    如果上述选项由于较低版本的 spark 无法正常工作,请尝试使用以下选项。

    --conf "spark.driver.extraJavaOptions=-Duser.timezone=UTC" --conf "spark.executor.extraJavaOptions=-Duser.timezone=UTC"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 2016-03-28
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多