简体   繁体   English

在EMR上使用Spark写入S3中的文件

[英]Write to a file in S3 using Spark on EMR

I use the following Scala code to create a text file in S3, with Apache Spark on AWS EMR. 我使用以下Scala代码在AWS EMR上使用Apache Spark在S3中创建文本文件。

def createS3OutputFile() {
    val conf = new SparkConf().setAppName("Spark Pi")
    val spark = new SparkContext(conf)
    // use s3n !
    val outputFileUri = s"s3n://$s3Bucket/emr-output/test-3.txt"
    val arr = Array("hello", "World", "!")
    val rdd = spark.parallelize(arr)
    rdd.saveAsTextFile(outputFileUri)
    spark.stop()
  }

def main(args: Array[String]): Unit = {
    createS3OutputFile()
  }

I create a fat JAR and upload it to S3. 我创建一个胖JAR并将其上传到S3。 I then SSH into the cluster master and run the code with: 然后,我通过SSH进入集群主服务器并使用以下代码运行代码:

spark-submit \
    --deploy-mode cluster \
    --class "$class_name" \
    "s3://$s3_bucket/$app_s3_key"

I am seeing this in the S3 console: instead of files there are folders. 我在S3控制台中看到了这一点:没有文件,而是文件夹。

在此处输入图片说明

Each folder (for example test-3.txt) contains a long list of block files. 每个文件夹(例如test-3.txt)包含一长串的阻止文件。 Picture below: 下图:

在此处输入图片说明

How do I output a simple text file to S3 as the output of my Spark job? 如何将简单文本文件输出到S3作为Spark作业的输出?

Try doing this: 尝试这样做:

rdd.coalesce(1, shuffle = true).saveAsTextFile(...)

My understanding is that the shuffle = true argument will cause this to occur in parallel so it will output a single text file, but do be careful with massive data files. 我的理解是shuffle = true参数将导致并行发生,因此将输出单个文本文件,但请注意大量数据文件。

Here are some more details on this issue at hand. 以下是有关此问题的更多详细信息。

Spark is distributed computing. Spark是分布式计算。 It means your code is running on multiple nodes. 这意味着您的代码正在多个节点上运行。

saveAsTextFile() method accepts file path , not the file name. saveAsTextFile()方法接受file path ,而不是文件名。

You could use coalesce () or repartition to decrease the number of part files. 您可以使用coalesce ()或repartition来减少零件文件的数量。 But still it will be created under the file path. 但是仍然会在文件路径下创建它。

Alternatively, you can change the file name or merge multiple part files to single part file, using FileUtil class from Hadoop File System . 或者,您可以使用Hadoop File System FileUtil类来更改文件名或将多个零件文件合并为单个零件文件。

Store RDD to S3 将RDD存储到S3

rdd.saveAsTextFile("s3n://bucket/path/")

Also, check this 另外,检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM