我有以下python3 avro程序:
import avro.schema
import json
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
write_schema = avro.schema.parse(json.dumps({
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}))
writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), write_schema)
writer.append({"name": "Alyssa", "favorite_number": 256})
writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"})
writer.close()
read_schema = avro.schema.parse(json.dumps({
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "first_name", "type": "string", "default": "", "aliases": ["name"]},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}))
reader = DataFileReader(open("users.avro", "rb"), DatumReader(write_schema, read_schema))
new_schema = reader.get_meta("avro.schema")
users = []
for user in reader:
users.append(user)
reader.close()
users
的内容如下:
[{'favorite_color': None, 'favorite_number': 256, 'first_name': ''},
{'favorite_color': 'red', 'favorite_number': 7, 'first_name': ''}]
我原本以为它会有'本''和' Alyssa'在first_name
字段中。这个库中的别名如何工作?这是否遵循规范?
答案 0 :(得分:1)
使用with
确实可以。这是使用该库的相同代码段:
fastavro
输出:
from io import BytesIO
from fastavro import reader, writer
write_schema = {
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}
records = [
{"name": "Alyssa", "favorite_number": 256},
{"name": "Ben", "favorite_number": 7, "favorite_color": "red"}
]
bio = BytesIO()
writer(bio, write_schema, records)
bio.seek(0)
read_schema = {
"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "first_name", "type": "string", "default": "", "aliases": ["name"]},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}
for record in reader(bio, read_schema):
print(record)
答案 1 :(得分:0)
遗憾的是,我现在发现标准avro软件包的python版本没有实现别名(https://issues.apache.org/jira/browse/AVRO-1303)。由于2013/2014年以来一直存在,我不希望很快就能获得标准修复。更有希望的是正在进行修复的fastavro项目。