Phi*_*ahl 11 arrays null optional avro
我想知道是否可以有一个可选的数组.让我们假设一个这样的架构:
{
"type": "record",
"name": "test_avro",
"fields" : [
{"name": "test_field_1", "type": "long"},
{"name": "subrecord", "type": [{
"type": "record",
"name": "subrecord_type",
"fields":[{"name":"field_1", "type":"long"}]
},"null"]
},
{"name": "simple_array",
"type":{
"type": "array",
"items": "string"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
尝试编写没有"simple_array"的avro记录会导致数据编写器中的NPE.对于subrecord,它很好,但是当我尝试将数组定义为可选时:
{"name": "simple_array",
"type":[{
"type": "array",
"items": "string"
}, "null"]
Run Code Online (Sandbox Code Playgroud)
它不会导致NPE,但会导致运行时异常:
AvroRuntimeException: Not an array schema: [{"type":"array","items":"string"},"null"]
Run Code Online (Sandbox Code Playgroud)
谢谢.
koj*_*iro 22
我想你想要的是null和数组的联合:
{
"type":"record",
"name":"test_avro",
"fields":[{
"name":"test_field_1",
"type":"long"
},
{
"name":"subrecord",
"type":[{
"type":"record",
"name":"subrecord_type",
"fields":[{
"name":"field_1",
"type":"long"
}
]
},
"null"
]
},
{
"name":"simple_array",
"type":["null",
{
"type":"array",
"items":"string"
}
],
"default":null
}
]
}
Run Code Online (Sandbox Code Playgroud)
当我在Python中使用上面的模式和示例数据时,这是结果(schema_string是上面的json字符串):
>>> from avro import io, datafile, schema
>>> from json import dumps
>>>
>>> sample_data = {'test_field_1':12L}
>>> rec_schema = schema.parse(schema_string)
>>> rec_writer = io.DatumWriter(rec_schema)
>>> rec_reader = io.DatumReader()
>>>
>>> # write avro file
... df_writer = datafile.DataFileWriter(open("/tmp/foo", 'wb'), rec_writer, writers_schema=rec_schema)
>>> df_writer.append(sample_data)
>>> df_writer.close()
>>>
>>> # read avro file
... df_reader = datafile.DataFileReader(open('/tmp/foo', 'rb'), rec_reader)
>>> print dumps(df_reader.next())
{"simple_array": null, "test_field_1": 12, "subrecord": null}
Run Code Online (Sandbox Code Playgroud)