PySpark中的列过滤

men*_*h84 6 python lambda apache-spark apache-spark-sql pyspark

我有一个df从Hive表加载的数据帧,它有一个时间戳列,比如说ts,字符串类型为格式dd-MMM-yy hh.mm.ss.MS a(转换为python datetime库,这是%d-%b-%y %I.%M.%S.%f %p).

现在我想过滤数据帧中过去五分钟的行:

only_last_5_minutes = df.filter(
    datetime.strptime(df.ts, '%d-%b-%y %I.%M.%S.%f %p') > datetime.now() - timedelta(minutes=5)
)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,我收到此消息

TypeError: strptime() argument 1 must be string, not Column
Run Code Online (Sandbox Code Playgroud)

看起来我有错误的列操作应用程序,在我看来,我必须创建一个lambda函数来过滤满足所需条件的每一列,但特别是Python和lambda表达式的新手,我不知道如何创建我的过滤器正确.请指教.

PS我更喜欢将我的过滤器表示为Python本机(或SparkSQL)而不是Hive sql查询表达式'WHERE'中的过滤器.

首选:

df = sqlContext.sql("SELECT * FROM my_table")
df.filter( // filter here)
Run Code Online (Sandbox Code Playgroud)

不是首选的:

df = sqlContext.sql("SELECT * FROM my_table WHERE...")
Run Code Online (Sandbox Code Playgroud)

zer*_*323 19

可以使用用户定义的功能.

from datetime import datetime, timedelta
from pyspark.sql.types import BooleanType, TimestampType
from pyspark.sql.functions import udf, col

def in_last_5_minutes(now):
    def _in_last_5_minutes(then):
        then_parsed = datetime.strptime(then, '%d-%b-%y %I.%M.%S.%f %p')
        return then_parsed > now - timedelta(minutes=5)
    return udf(_in_last_5_minutes, BooleanType())
Run Code Online (Sandbox Code Playgroud)

使用一些虚拟数据:

df = sqlContext.createDataFrame([
    (1, '14-Jul-15 11.34.29.000000 AM'),
    (2, '14-Jul-15 11.34.27.000000 AM'),
    (3, '14-Jul-15 11.32.11.000000 AM'),
    (4, '14-Jul-15 11.29.00.000000 AM'),
    (5, '14-Jul-15 11.28.29.000000 AM')
], ('id', 'datetime'))

now = datetime(2015, 7, 14, 11, 35)
df.where(in_last_5_minutes(now)(col("datetime"))).show()
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,我们只获得3个条目:

+--+--------------------+
|id|            datetime|
+--+--------------------+
| 1|14-Jul-15 11.34.2...|
| 2|14-Jul-15 11.34.2...|
| 3|14-Jul-15 11.32.1...|
+--+--------------------+
Run Code Online (Sandbox Code Playgroud)

再次解析日期时间字符串是相当低效的,因此您可以考虑存储TimestampType.

def parse_dt():
    def _parse(dt):
        return datetime.strptime(dt, '%d-%b-%y %I.%M.%S.%f %p')
    return udf(_parse, TimestampType())

df_with_timestamp = df.withColumn("timestamp", parse_dt()(df.datetime))

def in_last_5_minutes(now):
    def _in_last_5_minutes(then):
        return then > now - timedelta(minutes=5)
    return udf(_in_last_5_minutes, BooleanType())

df_with_timestamp.where(in_last_5_minutes(now)(col("timestamp")))
Run Code Online (Sandbox Code Playgroud)

结果:

+--+--------------------+--------------------+
|id|            datetime|           timestamp|
+--+--------------------+--------------------+
| 1|14-Jul-15 11.34.2...|2015-07-14 11:34:...|
| 2|14-Jul-15 11.34.2...|2015-07-14 11:34:...|
| 3|14-Jul-15 11.32.1...|2015-07-14 11:32:...|
+--+--------------------+--------------------+
Run Code Online (Sandbox Code Playgroud)

最后,可以使用带有时间戳的原始SQL查询:

query = """SELECT * FROM df
     WHERE unix_timestamp(datetime, 'dd-MMM-yy HH.mm.ss.SSSSSS a') > {0}
     """.format(time.mktime((now - timedelta(minutes=5)).timetuple()))

sqlContext.sql(query)
Run Code Online (Sandbox Code Playgroud)

与上面相同,解析日期字符串一次会更有效.

如果列已经是timestamp可以使用datetime文字:

from pyspark.sql.functions import lit

df_with_timestamp.where(
    df_with_timestamp.timestamp > lit(now - timedelta(minutes=5)))
Run Code Online (Sandbox Code Playgroud)

编辑

从Spark 1.5开始,您可以解析日期字符串,如下所示:

from pyspark.sql.functions import from_unixtime, unix_timestamp
from pyspark.sql.types import TimestampType

df.select((from_unixtime(unix_timestamp(
    df.datetime, "yy-MMM-dd h.mm.ss.SSSSSS aa"
))).cast(TimestampType()).alias("datetime"))
Run Code Online (Sandbox Code Playgroud)