【问题标题】:How to create a schema from JSON file using Spark Scala for subset of fields?如何使用 Spark Scala 从 JSON 文件为字段子集创建模式?
【发布时间】:2021-03-03 15:46:10
【问题描述】:

我正在尝试创建嵌套 JSON 文件的架构,以便它可以成为数据框。

但是,如果我只需要其中的“id”和“文本”——一个子集,我不确定是否有办法在不定义 JSON 文件中的所有字段的情况下创建架构。

我目前在 spark shell 中使用 scala。从文件中可以看出,我是从 HDFS 下载的 part-00000。

.

【问题讨论】:

  • 您能以 json 格式发布您的架构吗?像 df.schema.json 一样?
  • 不,我在 spark shell 中也不能。它要求我手动推断架构@Srinivas
  • 添加一些示例输入数据和预期输出
  • 关于你看的问题还是我的实际代码? @Srinivas
  • 如果您以 json 格式发布一些相同的数据,我们可以轻松地为您的问题提供更好的解决方案..

标签: json apache-spark apache-spark-sql spark-streaming


【解决方案1】:

来自 JSON 手册:

使用.schema 方法应用架构。此读取仅返回 架构中指定的列。

所以你可以按照你的暗示去做。

例如

import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType};
val schema = new StructType()
      .add("op_ts", StringType, true)

val df = spark.read.schema(schema)
              .option("multiLine", true).option("mode", "PERMISSIVE")
              .json("/FileStore/tables/json_stuff.txt")
df.printSchema()
df.show(false)

返回:

root
 |-- op_ts: string (nullable = true)

+--------------------------+
|op_ts                     |
+--------------------------+
|2019-05-31 04:24:34.000327|
+--------------------------+

对于这个架构:

root
 |-- after: struct (nullable = true)
 |    |-- CODE: string (nullable = true)
 |    |-- CREATED: string (nullable = true)
 |    |-- ID: long (nullable = true)
 |    |-- STATUS: string (nullable = true)
 |    |-- UPDATE_TIME: string (nullable = true)
 |-- before: string (nullable = true)
 |-- current_ts: string (nullable = true)
 |-- op_ts: string (nullable = true)
 |-- op_type: string (nullable = true)
 |-- pos: string (nullable = true)
 |-- primary_keys: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- table: string (nullable = true)
 |-- tokens: struct (nullable = true)
 |    |-- csn: string (nullable = true)
 |    |-- txid: string (nullable = true)

从同一个文件中获取:

val df = spark.read
              .option("multiLine", true).option("mode", "PERMISSIVE")
              .json("/FileStore/tables/json_stuff.txt")
df.printSchema()
df.show(false)

后者只是为了证明。

【讨论】:

  • @OoIJac,此解决方案应该可以解决您的问题.. 并支持详细信息.. :)
  • @Srinivas,我可以在 spark shell 中执行此操作吗?而且,这个解决方案只是帮助我定义了一个模式,那么我有没有办法将 json 文件中的字段连接到这个自定义模式中?
  • 简单的方法是从您的数据中获取实际架构并修改或删除不需要的列。然后使用该架构加载相同的数据。
  • @Srinivas 我不确定你的意思,第二部分只是展示整体架构并证明使用 .schema 选项也可以使用子集。
  • 然后你手动推断它,就像我展示的那样。问题是什么?没有。只需执行 .schema。但是要写出你必须知道的东西,你无法猜测。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 2021-01-08
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多