scala - 如何使用spark在数据框中创建模式数组

标签 scala apache-spark

我有创建数据框的代码,如果我的输入数据中没有数组,这可以正常工作。

我尝试使用没有数组的 Json 数据并且它运​​行成功。
我的代码是

val vals = sc.parallelize(
  """{"id":"1","name":"alex"}""" ::
  Nil
)

val schema = (new StructType)
      .add("id", StringType)
      .add("name", StringType)


  sqlContext.read.schema(schema).json(vals).select($"*").printSchema()

我的问题是,如果我有如下数组的输入数据,那么如何创建模式?
     val vals = sc.parallelize(
  """{"id":"1","name":"alex","score":[{"keyword":"read","point":10}]}""" ::
  Nil
)


val schema = (new StructType)
      .add("id", StringType)
      .add("name", StringType)

谢谢。

最佳答案

好的,我可以在我的代码中找到解决方案。

在数据框中创建数组中的模式 spark 您可以使用此代码。

val vals = sc.parallelize(
  """{"id":"1","name":"alex","score":[{"keyword":"read","point":10}]}""" ::
  Nil
)

val schema = StructType(
      Array(
        StructField("id", StringType),
        StructField("name", StringType),
        StructField("score", ArrayType(StructType(Array(
          StructField("keyword", StringType),
          StructField("point", IntegerType)
        ))))
      )
    )

然后你打印模式
sqlContext.read.schema(schema).json(vals).select($"*").printSchema()

谢谢已解决

关于scala - 如何使用spark在数据框中创建模式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39485374/

相关文章:

scala - 不同文件中的内部类

scala - 如何在 Scala 中定义 Tuple1?

json - 如何编写惯用的 Scala 包装类来表示非惯用的 JSON

apache-spark - java序列化与kryo序列化的优缺点是什么?

apache-spark - 在集群模式下在 Kubernetes 上提交 Spark 应用程序 : Configured service account doesn't have access

apache-spark - SparkSQL : Ignoring invalid json files

scala - akka 问题 Substream Source(EntitySource) 无法多次具体化

regex - Scala Spark 使用子字符串和字符过滤 DataFrame 中的行

scala - Spark程序性能——GC&任务反序列化&并发执行

apache-spark - 我怎么知道我的 Spark 工作是否在进行中?