Looking for a concise example on how to read and write Map<String, Object>
from/to parquet file in Java or Scala?
Here is expected structure, using com.fasterxml.jackson.databind.ObjectMapper
as serializer in Java (i.e. looking for equivalent using parquet):
public static Map<String, Object> read(InputStream inputStream) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(inputStream, new TypeReference<Map<String, Object>>() {
});
}
public static void write(OutputStream outputStream, Map<String, Object> map) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(outputStream, map);
}
i'm not quite good about parquet but, from here:
Schema schema = new Schema.Parser().parse(Resources.getResource("map.avsc").openStream());
File tmp = File.createTempFile(getClass().getSimpleName(), ".tmp");
tmp.deleteOnExit();
tmp.delete();
Path file = new Path(tmp.getPath());
AvroParquetWriter<GenericRecord> writer =
new AvroParquetWriter<GenericRecord>(file, schema);
// Write a record with an empty map.
ImmutableMap emptyMap = new ImmutableMap.Builder<String, Integer>().build();
GenericData.Record record = new GenericRecordBuilder(schema)
.set("mymap", emptyMap).build();
writer.write(record);
writer.close();
AvroParquetReader<GenericRecord> reader = new AvroParquetReader<GenericRecord>(file);
GenericRecord nextRecord = reader.read();
assertNotNull(nextRecord);
assertEquals(emptyMap, nextRecord.get("mymap"));
In your situation change ImmutableMap
(Google Collections) with a default Map as below:
Schema schema = new Schema.Parser().parse( Resources.getResource( "map.avsc" ).openStream() );
File tmp = File.createTempFile( getClass().getSimpleName(), ".tmp" );
tmp.deleteOnExit();
tmp.delete();
Path file = new Path( tmp.getPath() );
AvroParquetWriter<GenericRecord> writer = new AvroParquetWriter<GenericRecord>( file, schema );
// Write a record with an empty map.
Map<String,Object> emptyMap = new HashMap<String, Object>();
// not empty any more
emptyMap.put( "SOMETHING", new SOMETHING() );
GenericData.Record record = new GenericRecordBuilder( schema ).set( "mymap", emptyMap ).build();
writer.write( record );
writer.close();
AvroParquetReader<GenericRecord> reader = new AvroParquetReader<GenericRecord>( file );
GenericRecord nextRecord = reader.read();
assertNotNull( nextRecord );
assertEquals( emptyMap, nextRecord.get( "mymap" ) );
I didn't test the code, but give it a try..