【问题标题】:spark filter column from dataframe with words from a collection来自数据框的火花过滤器列以及来自集合的单词
【发布时间】:2017-04-26 08:41:49
【问题描述】:

我一直在寻找一段时间,但我还没有找到如何去做。 我有一个包含对表的引用的数据框,其中一列包含一个字符串

dataframe schema: name string,lastname string, interests string

我有一个这样的兴趣列表:

val sports:List [String] = List("football","basketball","soccer")

我想从我的数据框中过滤出所有符合他们兴趣的包含上述一项运动的人

val peopledata = sqlContext.sql("select * from learning.people")

我尝试过这样做:

for (sport <- sports)peopledata.filter(peopledata("interests").contains(sport))

但我已经问过我工作的公司的一位专业人士,他告诉我他有一个更好、更漂亮的方法来做这件事

【问题讨论】:

    标签: scala apache-spark hive bigdata


    【解决方案1】:

    执行collect()函数得到Array[Row]的结果并用sports.contains()过滤这个数组的元素:

    peopledata.collect().filter(row =&gt; sports contains row.getString(2))

    这里的 2 是架构中 interests 字段的数量。

    【讨论】:

    • 它说它需要一个 int 并且它返回一个字符串
    • @SparkHelpPlease 哎呀,修正了我的答案
    • 我发布了一个答案,然后意识到它有一个错误,因此将其删除,但需要提及的是,通过执行 collect,您会将所有 peopleData 移动到您的驱动程序,这可能没问题,只要它适合您的驱动程序的内存。另一种解决方案是 broadcast sports 并在 peopleData DataFrame 上进行过滤。恐怕我没时间了,但如果问题仍然存在,我会稍后再回来查看并发布解决方案:)
    【解决方案2】:

    使用字符串插值将解决您的问题:

    val interest  = sports.mkString("('","','","')")
    
    val peopledata = sqlContext.sql(s"select * from learning.people where interest in $interest")
    

    【讨论】:

    • 我认为这还不够,因为兴趣可以是这样的:"football,baseball" 等等在一个字符串中
    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2018-01-18
    • 2020-08-31
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多