在SparkConf 上设置压缩选项不是一个好的做法,作为公认的答案。它全局改变了行为,而不是基于每个文件指示设置。事实是,显式总是优于隐式。在某些情况下,用户无法轻松操作上下文配置,例如 spark-shell 或设计为另一个子模块的代码。
正确的方法
自 Spark 1.4 起支持使用压缩写入 DataFrame。实现这一目标的几种方法:
一个
df.write.json("filename.json", compression="gzip")
就是这样!随意使用DataFrameWriter.json()。
神奇隐藏在代码pyspark/sql/readwriter.py
@since(1.4)
def json(self, path, mode=None, compression=None, dateFormat=None, timestampFormat=None):
"""Saves the content of the :class:`DataFrame` in JSON format
(`JSON Lines text format or newline-delimited JSON <http://jsonlines.org/>`_) at the
specified path.
:param path: the path in any Hadoop supported file system
:param mode: ...
:param compression: compression codec to use when saving to file. This can be one of the
known case-insensitive shorten names (none, bzip2, gzip, lz4,
snappy and deflate).
:param dateFormat: ...
:param timestampFormat: ...
>>> df.write.json(os.path.join(tempfile.mkdtemp(), 'data'))
"""
self.mode(mode)
self._set_opts(
compression=compression, dateFormat=dateFormat, timestampFormat=timestampFormat)
self._jwrite.json(path)
支持的压缩格式有 bzip2、gzip、lz4、snappy 和 deflate,不区分大小写。
scala API 应该是一样的。
另一个
df.write.options(compression="gzip").json("filename.json")
同上。可以提供更多选项作为关键字参数。从 Spark 1.4 开始可用。
第三
df.write.option("compression", "gzip").json("filename.json")
DataFrameWriter.option() 从 Spark 1.5 开始添加。一次只能添加一个参数。