Объединение файлов JSON в фрейм данных с помощью spark/scala

#json #scala #apache-spark #apache-spark-sql

Вопрос:

Я пытаюсь объединить два файла json вместе и преобразовать их в фрейм данных. Приведенный ниже код распечатывает два кадра данных, один для 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.")
  }
}
 

Ответ №1:

почему бы вам просто не поместить оба ваших файла туда » /Пользователи/Рабочий стол/», и spark прочитает их и объединит, если схемы будут одинаковыми.

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

или поместите оба пути к файлам в список:

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