【问题标题】:find specific string in spark sql--pyspark在 spark sql--pyspark 中查找特定字符串
【发布时间】:2020-03-26 13:29:34
【问题描述】:

我试图在员工数据框的数据框列中找到完全匹配的字符串

Employee  days_present
Alex      1,2,11,23,
John      21,23,25,28

需要根据 days_present 列查找 2 日有哪些员工在场 预期输出: 亚历克斯

以下是我尝试过的

    df = spark.sql("select * from employee where days_present RLIKE '2')
    df.show()

This returns both Alex & John

另外我想知道谁在 2 和 11,在这种情况下,预期的输出只有 ALex

【问题讨论】:

  • 如果我们split()days_present 字段与,,然后分解生成的数组字段。这样,您就可以为所有员工提供一个包含天数的字段。

标签: pandas apache-spark pyspark-sql


【解决方案1】:

我们可以从 Spark-2.4+ 开始使用 array_intersect 函数,然后检查数组大小 if size >=2

Example:

df.show()
+--------+------------+
|Employee|days_present|
+--------+------------+
|    Alex|   1,2,11,23|
|    John| 21,23,25,28|
+--------+------------+
#DataFrame[Employee: string, days_present: string]

df.withColumn("tmp",split(col("days_present"),",")).\
withColumn("intersect",array_intersect(col("tmp"),array(lit("2"),lit("11")))).\
filter(size("intersect") >= 2).\
drop("tmp","intersect").\
show()

#+--------+------------+
#|Employee|days_present|
#+--------+------------+
#|    Alex|   1,2,11,23|
#+--------+------------+

In spark-sql:

df.createOrReplaceTempView("tmp")

spark.sql("""select Employee,days_present from (select *,size(array_intersect(split(days_present,","),array("2","11")))size from tmp)e where size >=2""").show()

#+--------+------------+
#|Employee|days_present|
#+--------+------------+
#|    Alex|   1,2,11,23|
#+--------+------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 2015-08-06
    相关资源
    最近更新 更多