You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark中按时间段及多条件过滤数据行的正确语法求助

解决Spark DataFrame时间区间筛选的语法问题

嘿,我来帮你搞定这个报错的问题,主要是几个语法和逻辑上的小问题,咱们一步步来修正:

首先说你代码里的错误点:

  • 变量赋值错误:Scala里变量/常量赋值用单等号=,而不是双等号==(==是用来做相等比较的),而且字符串要用双引号(单引号在Scala里表示单个字符)。
  • 比较运算符写错:Spark里的大于等于、小于等于运算符是>=和<=,不是你写的<==和>==。
  • 时间区间逻辑错误:你要筛选close_time在起止时间之间,正确的逻辑是close_time >= 起始时间 且 close_time <= 结束时间,而不是start period <= close_time >= end period(这个逻辑会变成close_time同时大于等于两个时间,不是区间筛选)。

修正后的正确代码:

// 用val定义不可变的时间常量,赋值用=,字符串用双引号
val StartTime = "2017-03-14"
val EndTime = "2017-03-14"

// 修正条件逻辑和运算符,用&&表示逻辑与
val df1 = df.withColumn(
  "X_Field",
  when(
    $"category" === "incident" && 
    $"origin" === "phone" && 
    $"close_time" >= StartTime && 
    $"close_time" <= EndTime,
    1
  ).otherwise(0)
)

额外优化:如果close_time是Timestamp类型

如果你的close_time字段是Timestamp类型,建议把起止时间也转换成Timestamp类型,避免类型不匹配的问题:

import org.apache.spark.sql.functions.{to_timestamp, lit}

// 将字符串时间转成Timestamp类型
val StartTime = to_timestamp(lit("2017-03-14"))
val EndTime = to_timestamp(lit("2017-03-14"))

val df1 = df.withColumn(
  "X_Field",
  when(
    $"category" === "incident" && 
    $"origin" === "phone" && 
    $"close_time" >= StartTime && 
    $"close_time" <= EndTime,
    1
  ).otherwise(0)
)

内容的提问来源于stack exchange,提问作者Arij SEDIRI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:11:24