【问题标题】:How to convert Parquet file to Protobuf and save it HDFS/AWS S3如何将 Parquet 文件转换为 Protobuf 并将其保存在 HDFS/AWS S3
【发布时间】:2021-03-06 05:15:56
【问题描述】:

我有一个 Parquet 格式的文件。我想使用带有 Scala 的 spark 阅读并以 Protobuf 格式将其保存在 HDFS 或 AWS S3 中。我不确定有什么办法。搜索了很多博客,但什么都看不懂,谁能帮忙?

【问题讨论】:

  • 您打算如何阅读它们?你想把它们写成序列文件吗?
  • 其实我想尝试多个选项,第一个写为序列文件,第二个写为 Protobuf。哪个工作得更快

标签: scala apache-spark protocol-buffers parquet


【解决方案1】:

您可以使用 ProtoParquetReader,它是带有 ProtoReadSupport 的 ParquetReader。

类似:

       try (ParquetReader reader = ProtoParquetReader.builder(path).build()
        ) {
            while ((model = reader.read()) != null){
                System.out.println("check model " + "-- " + model);
...
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

【讨论】:

  • 你能解释一下吗?
【解决方案2】:

为了从 parquet 中读取,您需要使用以下代码:

public List<Record> read(Path path) {
     List<Record> records = new ArrayList<>();
     ParquetReader<Record> reader = AvroParquetReader<Record>builder(path).withConf(new Configuration()).build();
            for (Record value = reader.read(); value != null; value = reader.read()) {
                records.add(value);
            }
            return records;
}

从 parquet 写入文件是这样的。虽然这不是 protobuf 文件,但这可能会帮助您入门。请记住,如果您最终将 spark-stream 与 protobuf v2.6 及更高版本一起使用,则会遇到问题

public void write(List<Record> records, String location) throws IOException {
        Path filePath = new Path(location);

        try (ParquetWriter<Record> writer = AvroParquetWriter.<GenericData.Record>builder(filePath)
            .withSchema(getSchema()) //
            .withConf(getConf()) //
            .withCompressionCodec(CompressionCodecName.SNAPPY) //
            .withWriteMode(Mode.CREATE) //
            .build()) {
            for (Record record : records) {
                writer.write(record);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2022-11-23
    • 2022-01-17
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多