Scala 数据帧 : Explode an array

标签 scala dataframe explode apache-spark-sql

我在 Scala 中使用 spark 库。我创建了一个 DataFrame 使用

val searchArr = Array(
  StructField("log",IntegerType,true),
  StructField("user", StructType(Array(
    StructField("date",StringType,true),
    StructField("ua",StringType,true),
    StructField("ui",LongType,true))),true),
  StructField("what",StructType(Array(
    StructField("q1",ArrayType(IntegerType, true),true),
    StructField("q2",ArrayType(IntegerType, true),true),
    StructField("sid",StringType,true),
    StructField("url",StringType,true))),true),
  StructField("where",StructType(Array(
    StructField("o1",IntegerType,true),
    StructField("o2",IntegerType,true))),true)
)

val searchSt = new StructType(searchArr)    

val searchData = sqlContext.jsonFile(searchPath, searchSt)

我现在是什么 explode 字段what.q1,它应该包含一个整数数组,但文档有限:
http://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/DataFrame.html#explode(java.lang.String,%20java.lang.String,%20scala.Function1,%20scala.reflect.api.TypeTags.TypeTag)

到目前为止,我尝试了几件事,但运气不佳
val searchSplit = searchData.explode("q1", "rb")(q1 => q1.getList[Int](0).toArray())

关于如何在数组上使用 explode 的任何想法/示例?

最佳答案

您是否尝试在“什么”字段上使用 UDF?类似的东西可能有用:

val explode = udf {
(aStr: GenericRowWithSchema) => 
  aStr match {
      case null => ""
      case _  =>  aStr.getList(0).get(0).toString()
  }
}


val newDF = df.withColumn("newColumn", explode(col("what")))

在哪里:
  • getList(0) 返回“q1”字段
  • 获取(0) 返回“q1”的第一个元素

  • 我不确定,但您可以尝试使用 getAs[T](fieldName: String) 而不是 getList(index: Int) .

    关于Scala 数据帧 : Explode an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31139927/

    相关文章:

    python - pandas2ri.ri2py_dataframe(r_dataframe) 返回 float 而不是 ISO-8601 (YYYY-MM-DD) 格式的日期

    scala - 如何在类中使用 Scala 枚举

    python - 根据指定的 START_DATE 和 END_DATE 从单独的 df 对 Pandas df 进行分组

    python - 应用具有更新值的 lambda 函数

    PHP从第一个数字(整数) explode

    php - MySQL跨表查询3张表,空值显示格子

    php - 如何分解键值对并在查询中使用它们

    javascript - scala play框架2.0.4中未选中的复选框无法设置为由Jquery或Javascript检查?

    java.util.list 作为 scala 类方法中的参数在 Java 代码中使用

    scala - 参数数量可变的Spark Sql udf