我有一个使用org.apache.parquet.hadoop.ParquetWriter将CSV数据文件转换为 Parquet 数据文件的工具。

我可以编写基本的基本类型(INT32,DOUBLE,BINARY字符串)。

我需要写NULL值,但我不知道如何。我尝试用ParquetWriter编写null,但它引发了异常。

如何使用org.apache.parquet.hadoop.ParquetWriter写入NULL?有可为空的类型吗?

我认为该代码是不言自明的:

    ArrayList<Type> fields = new ArrayList<>();
    fields.add(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveTypeName.INT32, "int32_col", null));
    fields.add(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveTypeName.DOUBLE, "double_col", null));
    fields.add(new PrimitiveType(Type.Repetition.OPTIONAL, PrimitiveTypeName.BINARY, "string_col", null));
    MessageType schema = new MessageType("input", fields);

    Configuration configuration = new Configuration();
    configuration.setQuietMode(true);
    GroupWriteSupport.setSchema(schema, configuration);
    SimpleGroupFactory f = new SimpleGroupFactory(schema);
    ParquetWriter<Group> writer = new ParquetWriter<Group>(
      new Path("output.parquet"),
      new GroupWriteSupport(),
      CompressionCodecName.SNAPPY,
      ParquetWriter.DEFAULT_BLOCK_SIZE,
      ParquetWriter.DEFAULT_PAGE_SIZE,
      1048576,
      true,
      false,
      ParquetProperties.WriterVersion.PARQUET_1_0,
      configuration
    );

    // create row 1 with defined values
    Group group1 = f.newGroup();
    Integer int1 = 100;
    Double double1 = 0.5;
    String string1 = "string-value";
    group1.add(0, int1);
    group1.add(1, double1);
    group1.add(2, string1);
    writer.write(group1);

    // create row 2 with NULL values -- does not work!
    Group group2 = f.newGroup();
    Integer int2 = null;
    Double double2 = null;
    String string2 = null;
    group2.add(0, int2); // <-- throws NullPointerException
    group2.add(1, double2); // <-- throws NullPointerException
    group2.add(2, string2); // <-- throws NullPointerException
    writer.write(group2);

    writer.close();

最佳答案

该解决方案非常简单,只是不写任何值:

// create row 1 with defined values
Group group1 = f.newGroup();
Integer int1 = 100;
Double double1 = 0.5;
String string1 = "string-value";
group1.add(0, int1);
group1.add(1, double1);
group1.add(2, string1);
writer.write(group1);

// create row 2 with NULL values -- does not work!
Group group2 = f.newGroup();
// do nothing !
writer.write(group2);

// Now, parquet file will have 2 rows, one with values, one with null values

07-23 12:50