ablog

不器用で落着きのない技術者のメモ

SparkSQL メモ

DataFrame を SparkSQL で操作する
  • サンプル
df.registerTempTable('table1')
df_res = spark.sql('select * from table1')
df_res.show()
Timestamp 型に変更する
  • やりたいこと
    • Dataframe で "2020-06-14T12:47:54+00:00" といったデータが string 型と認識されている場合に、timestamp 型に変換する。
  • サンプル
df_res = spark.sql('SELECT timestamp(sendAt) FROM raw_log')
  • 参考

timestamp
timestamp(expr) - Casts the value expr to the target data type timestamp.

Functions - Spark SQL, Built-in Functions
Timestamp 型のデータを分で丸める
  • やりたいこと
    • タイムスタンプ型のデータを分で丸めたい。
    • 例えば、2020-06-14 12:22:41 を 2020-06-14 12:22 と分レベルに丸めたい。
  • サンプル
df_res = spark.sql('SELECT date_trunc("minute", timestamp(sendAt)) FROM raw_log')
df_res.show()
+---------------------------------------------+
|date_trunc(minute, CAST(sendAt AS TIMESTAMP))|
+---------------------------------------------+
|                          2020-06-14 12:22:00|
|                          2020-06-14 12:22:00|
(中略)
|                          2020-06-14 12:22:00|
+---------------------------------------------+
only showing top 20 rows
  • 参考

date_trunc
date_trunc(fmt, ts) - Returns timestamp ts truncated to the unit specified by the format model fmt. fmt should be one of ["YEAR", "YYYY", "YY", "MON", "MONTH", "MM", "DAY", "DD", "HOUR", "MINUTE", "SECOND", "WEEK", "QUARTER"]

Examples:

> SELECT date_trunc('2015-03-05T09:32:05.359', 'YEAR');
 2015-01-01T00:00:00
> SELECT date_trunc('2015-03-05T09:32:05.359', 'MM');
 2015-03-01T00:00:00
> SELECT date_trunc('2015-03-05T09:32:05.359', 'DD');
 2015-03-05T00:00:00
> SELECT date_trunc('2015-03-05T09:32:05.359', 'HOUR');
 2015-03-05T09:00:00
Functions - Spark SQL, Built-in Functions