apache-spark - 在 Spark 应用程序中保存 RDD 的元素

标签 apache-spark pyspark rdd

我正在集群上运行 Spark 应用程序。我想对 RDD 中的每个元素执行一些操作并将每个元素保存到文本文件中。

我正在 myRDD 上调用 foreach

  myRDD.foreach(process)

   def process(elements):
        // some operation that extracts the strings
        // and converts to myList
        myList = ... 

        with open("somefile.txt", "a+") as myfile:
            print "----SAVED----"
            myfile.writelines(myList)

但是,即使我确实发现打印语句打印时没有任何错误/警告,我也无法找到 somefile.txt。 somefile.txt 保存在哪里?如果我的方法不正确,我该如何保存RDD的各个元素?

最佳答案

myRDD.map(convertToList).saveAsTextFile(<hdfs output path>)

通过这种方法,您将能够扩展您的应用程序,如果您必须将所有数据传输到驱动程序中,那么您将保证输出数据足够小以适合驱动程序内存,否则您将开始遇到麻烦。

如果您要求所有数据仅以一个文件结尾(这种方法与将所有输出传输到驱动程序有类似的问题,不可扩展):

myRDD.map(generateList).coalesce(1).saveAsTextFile(<hdfs output path>)

如果您需要在将列表存储在文件中之前将其转换为字符串,则:

myRDD.map(generateList).map(listToString).saveAsTextFile(<hdfs output path>)

显然,您可以将列表转换为第一个 map 内的字符串并节省额外的步骤。

关于apache-spark - 在 Spark 应用程序中保存 RDD 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953576/

相关文章:

caching - Spark SQL : how to cache sql query result without using rdd. 缓存()

apache-spark - 在 Spark 中显示 <IPython.core.display.HTML object>

apache-spark - Apache Spark 优化

python - 在 pyspark 数据框中,当我重命名列时,以前的名称仍可用于过滤。错误或功能?

java - 比较 RDD 对象 - Apache Spark

apache-spark - 使用Spark运行python脚本时出错

scala - 如何使用 RowMatrix.columnSimilarities(相似性搜索)

python - Pyspark:如何在数据框中复制一行 n 次?

python - 使用 groupby 或 aggregate 合并 RDD 或 DataFrame 中每个事务中的项目来做 FP-growth

python - 理论上,对于 Apache Spark,Scala 比 Python 更快。实际上并非如此。这是怎么回事?