首页 > 解决方案 > 从列表中搜索数据框以及在 Scala 的新列中找到的所有元素

问题描述

我有一个 df,我需要搜索关键字列表中是否有任何元素集.. 如果是,我需要将所有这些关键字 @ 分隔在一个名为 found 或 not 的新列中。

我的df就像

utid | description
123  | my name is harry and I live in newyork
234  | my neighbour is daniel and he plays hockey

该列表非常大,例如 list ={harry,daniel,hockey,newyork}

输出应该像

utid | description                                | foundornot
123  | my name is harry and I live in newyork     | harry@newyork
234  | my neighbour is daniel and he plays hockey | daniel@hockey

该列表非常大,例如一些 20k 关键字 ..如果找不到打印 NF

标签: scalaapache-sparkapache-spark-sql

解决方案


您可以检查listif exists 函数中每一行列中descriptionudf元素,并将元素列表作为由@分隔的字符串以将其返回,否则将NF字符串作为

val list = List("harry","daniel","hockey","newyork")

import org.apache.spark.sql.functions._
def checkUdf = udf((strCol: String) => if (list.exists(strCol.contains)) list.filter(strCol.contains(_)).mkString("@") else "NF")

df.withColumn("foundornot", checkUdf(col("description"))).show(false)

这应该给你

+----+------------------------------------------+-------------+
|utid|description                               |foundornot   |
+----+------------------------------------------+-------------+
|123 |my name is harry and i live in newyork    |harry@newyork|
|234 |my neighbour is daniel and he plays hockey|daniel@hockey|
+----+------------------------------------------+-------------+

推荐阅读