【问题标题】:Joining JSON files into a dataframe using spark/scala使用 spark/scala 将 JSON 文件加入数据框
【发布时间】:2021-09-29 18:21:48
【问题描述】:

我正在尝试将两个 json 文件连接在一起并转换为 DataFrame。下面的代码打印出两个 DataFrame,一个用于 test_1.json,另一个用于 test_2.json,但是它们没有连接在一起。

这是连接在一起的一段代码:谁能发现我做错了什么?

//CODE TO JOIN THE TWO JSON FILES TOGETHER

    users_df_2.join(users_df_1,"table").createOrReplaceTempView("new_table")

   val results = spark.sql("SELECT Scenerio, table, case WHEN gender = 'F' then 'Female' WHEN gender = 'M' then 'Male' END as gender from new_table")
package com.test.dataframe

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}

object dataframe {
  def main(args: Array[String]): Unit = {
    println("Apache Spark Application Started ...")

    val spark = SparkSession.builder()
      .appName("Create DataFrame from json File")
      .master("local[*]")
      .getOrCreate()

    spark.sparkContext.setLogLevel("ERROR")

    //Code Block 1 Starts Here
    val json_file_path = "/Users/Desktop/test_1.json"
    val users_df_1 = spark.read.json(json_file_path)

    users_df_1.show(10, true)
    users_df_1.printSchema()
    //Code Block 1 Ends Here

    //Code Block 2 Starts Here
    val json_multiline_file_path = "/Users/Desktop/test_2.json"

    val user_schema = StructType(Array(
      StructField("Scenerio", StringType, true),
      StructField("table", StringType, true)
    ))

    val users_df_2 = spark.read.option("multiLine", "true").json(json_multiline_file_path)

    users_df_2.show(10, false)
    users_df_2.printSchema()
    //Code Block 2 Ends Here

    //CODE TO JOIN THE TWO JSON FILES TOGETHER

    users_df_2.join(users_df_1,"table").createOrReplaceTempView("new_table")

   val results = spark.sql("SELECT Scenerio, table, case WHEN gender = 'F' then 'Female' WHEN gender = 'M' then 'Male' END as gender from new_table")

    spark.stop()
    println("Apache Spark Application Completed.")
  }
}

【问题讨论】:

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


    【解决方案1】:

    你为什么不把你的两个文件都放在那里'/Users/Desktop/',只要架构相同,spark 就会读入并组合它们。

    val df = spark.read.option("multiLine", "true").json('/Users/Desktop/')
    

    或将两个文件路径放在一个列表中:

    val df = sc.read.json(file1, file2, ...)
    

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-05-23
      • 2021-04-17
      • 2020-09-04
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多