学习 Parquet(二):Java API

依赖

编辑 pom.xml 文件,添加依赖:

<dependency>  
  <groupId>org.apache.parquet</groupId>
  <artifactId>parquet-avro</artifactId>
  <version>1.10.1</version>
</dependency>  

写入

Schema

Parquet 是结构化的文件结构,需要先定义 Schema。以定义 id long, name string 结构的 Schema 为例:

List<Schema.Field> fields = new ArrayList<>(2);  
fields.add(new Schema.Field("id", Schema.create(Schema.Type.LONG), "id", null));  
fields.add(new Schema.Field("name", Schema.create(Schema.Type.STRING), "name", null));  
Schema schema = Schema.createRecord(fields);  

Schema 支持的类型,定义在枚举 org.apache.avro.Schema.Type 中:

public enum Type {  
  RECORD, ENUM, ARRAY, MAP, UNION, FIXED, STRING, BYTES,
    INT, LONG, FLOAT, DOUBLE, BOOLEAN, NULL;
  private String name;
  private Type() { this.name = this.name().toLowerCase(Locale.ENGLISH); }
  public String getName() { return name; }
}

其中,RECORDENUMARRAYMAPUNIONFIXED 是复合类型,STRINGBYTESINTLONGFLOATBOOLEANNULL 是基本类型。

Writer

有了 Schema 之后,就可以写入文件了:

ParquetWriter<GenericData.Record> writer = AvroParquetWriter.<GenericData.Record>builder(path)  
    .withSchema(schema)
    .build();

GenericData.Record record = new GenericData.Record(schema);  
record.put(0, 0);  
record.put(1, "this is a test.");  
writer.write(record);

writer.close();  

读取

ParquetReader<GenericData.Record> reader = AvroParquetReader.<GenericData.Record>builder(path).build();  
GenericData.Record record = reader.read();  
reader.close();