spark:如何从scala中的arraytype对象中获取单个对象

tvokkenx  于 2021-07-12  发布在  Spark
关注(0)|答案(2)|浏览(293)

我有一个带有多列的df,其中一列在arraytype中,名为“requests”,其中包含两个字段“id”和“responses”:

(requests,ArrayType(StructType(StructField(id,IntegerType,true),StructField(responses,ArrayType(IntegerType,false),true))))

从一个“requests”数组中,我想得到一个“id”与特定值匹配的请求,并将其添加到一个新列中。
到目前为止,我添加了一个布尔值来表示该值是否存在于列表中:

dF
  .withColumn("idPresent", array_contains(col("requests.id"), 55))
  .show()

但当我把“id”作为参数时,我不知道怎样才能得到一个请求类型的对象?我希望数组中只存在一个这样的对象,但是如果不止一个,第一个就足够了。我想将新的匹配对象添加到新列中。

gcxthw6b

gcxthw6b1#

扩展@leo c的答案,您还可以使用 filter 要根据数组元素的id筛选它们,请执行以下操作:

df.withColumn("request_id2", expr("filter(requests, r -> r.id = 2)")).show(false)
+-------------------------------------+---------------+
|requests                             |request_id2    |
+-------------------------------------+---------------+
|[[1, [11]], [2, [21, 22]], [3, [31]]]|[[2, [21, 22]]]|
|[[4, [41, 42, 43]], [5, [51, 52]]]   |[]             |
+-------------------------------------+---------------+

如果只需要第一个struct对象,可以添加 [0]expr :

df.withColumn("request_id2", expr("filter(requests, r -> r.id = 2)[0]")).show(false)
+-------------------------------------+-------------+
|requests                             |request_id2  |
+-------------------------------------+-------------+
|[[1, [11]], [2, [21, 22]], [3, [31]]]|[2, [21, 22]]|
|[[4, [41, 42, 43]], [5, [51, 52]]]   |null         |
+-------------------------------------+-------------+
3gtaxfhh

3gtaxfhh2#

考虑使用高阶函数 transform 取消与“id”不匹配的请求,然后用 array_except :

case class Request(id: Int, responses: Seq[Int])

val df = Seq(
  Seq(Request(1, Seq(11)), Request(2, Seq(21, 22)), Request(3, Seq(31))),
  Seq(Request(4, Seq(41, 42, 43)), Request(5, Seq(51, 52)))
).toDF("requests")

df.
  withColumn("request_id2", array_except(
      expr("transform(requests, r -> case when r.id = 2 then r end)"),
      array(lit(null))
    )
  ).show(false)
// +-------------------------------------+---------------+
// |requests                             |request_id2    |
// +-------------------------------------+---------------+
// |[[1, [11]], [2, [21, 22]], [3, [31]]]|[[2, [21, 22]]]|
// |[[4, [41, 42, 43]], [5, [51, 52]]]   |[]             |
// +-------------------------------------+---------------+

相关问题