【问题标题】:Read two different files from Scala Spark in single code在单个代码中从 Scala Spark 读取两个不同的文件
【发布时间】:2020-08-26 20:53:57
【问题描述】:

我有两组文件和架构,我想在一组代码中运行它。

这是我的代码:

val file_path = "file1" // I want to pass two files (file1, file2)
val rdd = spark.sparkContext.wholeTextFiles(file_path)
val validJsonRdd = rdd.flatMap(_._2.replace(" ", "").replace("\n", "").replace(":value", ":\"value\"").replace("}{", "}\n{").split("\n"))
val dataframe = spark
      .read
      .option("multiLine", true)
      .schema(Schema1) // I want to put schema1 for file1 and schema2 for file2
      .json(validJsonRdd)
      .show()

所以按照上面的代码,我想运行两个不同的模式和它们对应的文件。

【问题讨论】:

  • 在您的 spark 作业中传递文件位置(file1 或 file2)和 schemahint(true 或 false)作为命令参数并相应地使用它...如果 schemahint 为 true,则在您的代码中设置 Schema1,否则设置 Schema2。
  • 我完全不熟悉它,我可以得到一个样本 sn-p

标签: scala apache-spark


【解决方案1】:

您可以将应用程序参数传递给 spark-submit,如下所示..

spark-submit的一般语法

./bin/spark-submit \
      --class <main-class> \
      --master <master-url> \
      --deploy-mode <deploy-mode> \
      --conf <key>=<value> \
      ... # other options
      <application-jar> \
      [application-arguments]

您可以使用 file.txt schema1.txt (OR) file1.txt 代替 [application-arguments] scehma2.txt

file.txt 是第一个参数,schema1.txt 是第二个参数。

在您的应用程序代码中,您可以这样做

 def main(args: Array[String]) : Unit = {
     val inputFile = args(0);
     val schemaFile = args(1);
     val schemaFileasString = // open FileInoutStream and read whole schema data from **schemaFile** as string 
     val schema = SchemaConverter.convertContent(schemaFileasString)
     //create spark session and provide all the parameter properly
    import spark.implicits._
    val rdd = spark.sparkContext.wholeTextFiles(inputFile)
    val validJsonRdd = rdd.flatMap(_._2.replace(" ", "").replace("\n", "").replace(":value", ":\"value\"").replace("}{", "}\n{").split("\n"))

     spark.read
      .option("multiLine", true)
      .schema(schema)
      .json(validJsonRdd)
      .show()
   }

参考资料:

https://github.com/zalando-incubator/spark-json-schema

https://spark.apache.org/docs/latest/submitting-applications.html

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2013-10-17
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多