控制配置设置 Apache Spark UTF 编码以写入为 saveAsTextFile

2024-01-12

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


saveAsTextFile实际上使用Text来自hadoop,编码为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 我想你可以使用saveAsHadoopFile with org.apache.hadoop.io.BytesWritable并获取 java 的字节String(正如你所说,这将是 UTF-16)。像这样的事情:
saveAsHadoopFile[SequenceFileOutputFormat[NullWritable, BytesWritable]](path)
您可以从以下位置获取字节"...".getBytes("UTF-16")

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

控制配置设置 Apache Spark UTF 编码以写入为 saveAsTextFile 的相关文章

随机推荐