【问题标题】:Spark: Query for multiple conditions at the same timeSpark:同时查询多个条件
【发布时间】:2020-06-18 20:29:09
【问题描述】:

所以Dataframe.where 可用于过滤由表达式给出的行的数据框,如下所示:

df.where(($"group_id" == 1234) || ($"group_id" == 4434))

或者举个更复杂的例子

df.where(($"group_id" == 1234 && $"country" === "PL") || ($"group_id" == 4434 $"country" === "FR"))

我对是否可以以某种方式提供这些条件作为列表感兴趣,所以假设我有一个 group_id 的列表,List((1234, "PL"), (4434, "FR"), ....) 然后我想有效地过滤数据框。

【问题讨论】:

    标签: scala dataframe apache-spark


    【解决方案1】:

    你可以试试这样的:

    val df = Seq((1,"a"),(2,"b"),(3,"c")).toDF()
    df.show()
    

    +---+---+
    | _1| _2|
    +---+---+
    |  1|  a|
    |  2|  b|
    |  3|  c|
    +---+---+
    

    val list = List((1,"a"),(3,"c"))
    val cols = List("_1","_2")
    
    def mkCol(values: List[(Any,Any)], columns: List[String]) = list.map(s=>col(columns.apply(0)) === s._1 && col(columns.apply(1)) === s._2)
                                                                    .reduce((a,b)=>a.or(b))
    
    val col = mkCol(list,cols)
    col.explain(true)
    

    ((('_1 = 1) && ('_2 = a)) || (('_1 = 3) && ('_2 = c)))
    

    df.where(col).show()
    

    +---+---+
    | _1| _2|
    +---+---+
    |  1|  a|
    |  3|  c|
    +---+---+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 2021-09-03
      • 2021-12-13
      相关资源
      最近更新 更多