【问题标题】:Control configure set Apache Spark UTF encoding for writting as saveAsTextFile控制配置设置 Apache Spark UTF 编码以写入 saveAsTextFile
【发布时间】:2014-07-09 11:04:29
【问题描述】:

那么在使用saveAsTextFile(path) 时如何告诉spark 使用哪种UTF?当然,如果知道所有字符串都是 UTF-8,那么它将节省 2 倍的磁盘空间! (假设默认的 UTF 像 java 一样是 16)

【问题讨论】:

  • 我会说只是使用hadoop输出格式,saveAsTextFile除了文件名外不带任何参数

标签: scala utf-8 apache-spark utf


【解决方案1】:

saveAsTextFile 实际上使用了 hadoop 中的Text,编码为 UTF-8。

def saveAsTextFile(path: String, codec: Class[_ <: CompressionCodec]) {
    this.map(x => (NullWritable.get(), new Text(x.toString)))
      .saveAsHadoopFile[TextOutputFormat[NullWritable, Text]](path, codec)
  }

来自 Text.java:

public class Text extends BinaryComparable
    implements WritableComparable<BinaryComparable> {

  static final int SHORT_STRING_MAX = 1024 * 1024;

  private static ThreadLocal<CharsetEncoder> ENCODER_FACTORY =
    new ThreadLocal<CharsetEncoder>() {
      protected CharsetEncoder initialValue() {
        return Charset.forName("UTF-8").newEncoder().
               onMalformedInput(CodingErrorAction.REPORT).
               onUnmappableCharacter(CodingErrorAction.REPORT);
    }
  };

  private static ThreadLocal<CharsetDecoder> DECODER_FACTORY =
    new ThreadLocal<CharsetDecoder>() {
    protected CharsetDecoder initialValue() {
      return Charset.forName("UTF-8").newDecoder().
             onMalformedInput(CodingErrorAction.REPORT).
             onUnmappableCharacter(CodingErrorAction.REPORT);
    }
  };

如果您想保存为 UTF-16,我认为您可以使用 saveAsHadoopFileorg.apache.hadoop.io.BytesWritable 并获取 java String 的字节(正如您所说的将是 UTF-16)。像这样的东西:
saveAsHadoopFile[SequenceFileOutputFormat[NullWritable, BytesWritable]](path)
你可以从"...".getBytes("UTF-16")获取字节

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多