fastavro
, альтернативная реализация Python, прекрасно справляется с этим.
Код для записи с первой схемой находится здесь:
s1 = {
"type": "record",
"namespace": "com.example",
"name": "CustomerV1",
"fields": [
{"name": "first_name", "type": "string", "doc": "First Name of Customer"},
{"name": "last_name", "type": "string", "doc": "Last Name of Customer"},
{"name": "age", "type": "int", "doc": "Age at the time of registration"},
{
"name": "height",
"type": "float",
"doc": "Height at the time of registration in cm",
},
{
"name": "weight",
"type": "float",
"doc": "Weight at the time of registration in kg",
},
{
"name": "automated_email",
"type": "boolean",
"default": True,
"doc": "Field indicating if the user is enrolled in marketing emails",
},
],
}
record = {
"first_name": "John",
"last_name": "Doe",
"age": 34,
"height": 178.0,
"weight": 75.0,
"automated_email": True,
}
import fastavro
with open("test.avro", "wb") as fp:
fastavro.writer(fp, fastavro.parse_schema(s1), [record])
И читать со второй схемой:
s2 = {
"type": "record",
"namespace": "com.example",
"name": "CustomerV2",
"fields": [
{"name": "first_name", "type": "string", "doc": "First Name of Customer"},
{"name": "last_name", "type": "string", "doc": "Last Name of Customer"},
{"name": "age", "type": "int", "doc": "Age at the time of registration"},
{
"name": "height",
"type": "float",
"doc": "Height at the time of registration in cm",
},
{
"name": "weight",
"type": "float",
"doc": "Weight at the time of registration in kg",
},
{
"name": "phone_number",
"type": ["null", "string"],
"default": None,
"doc": "optional phone number",
},
{
"name": "email",
"type": "string",
"default": "missing@example.com",
"doc": "email address",
},
],
}
import fastavro
with open("test.avro", "rb") as fp:
for record in fastavro.reader(fp, fastavro.parse_schema(s2)):
print(record)
Вывод в виде новых полей, как и ожидалось:
{'first_name': 'John', 'last_name': 'Doe', 'age': 34, 'height': 178.0, 'weight': 75.0, 'phone_number': None, 'email': 'missing@example.com'}