【发布时间】:2020-03-25 03:26:58
【问题描述】:
我正在尝试在 Avro 中使用逻辑类型,使用 Python fastavro 库进行读写,但 logicalType 注释似乎根本没有效果。下面的代码取自fastavro page;根据the current Avro specification,我通过使用逻辑类型time-millis 注释模式定义中的time 字段来更改它。 (顺便说一句,我看到人们使用 TIMESTAMP_MILLIS,但我不知道为什么,因为 Avro 页面有 time-millis。)当我运行这段代码时,我在 stdout 中看到的输出与没有逻辑类型注释的相同代码的输出完全相同。我期待看到一些看起来像时间的东西——例如,13:14:15.1234。然而,上面引用的 fastavro 页面声称 fastavro 现在支持 Avro 逻辑类型。我怎样才能让它这样做?谢谢!
from fastavro import writer, reader, parse_schema
schema = {
'doc': 'A weather reading.',
'name': 'Weather',
'namespace': 'test',
'type': 'record',
'fields': [
{'name': 'station', 'type': 'string'},
{'name': 'time', 'type': 'int', 'logicalType': 'time-millis'},
{'name': 'temp', 'type': 'int'},
],
}
parsed_schema = parse_schema(schema)
# 'records' can be an iterable (including generator)
records = [
{u'station': u'011990-99999', u'temp': 0, u'time': 1433269388},
{u'station': u'011990-99999', u'temp': 22, u'time': 1433270389},
{u'station': u'011990-99999', u'temp': -11, u'time': 1433273379},
{u'station': u'012650-99999', u'temp': 111, u'time': 1433275478},
]
# Writing
with open('weather.avro', 'wb') as out:
writer(out, parsed_schema, records)
# Reading
with open('weather.avro', 'rb') as fo:
for record in reader(fo):
print(record)
到标准输出的输出,无论logicalType注解是存在还是移除,都是一样的:
“站”:“011990-99999”,“时间”:1433269388,“温度”:0}
{'station': '011990-99999', 'time': 1433270389, 'temp': 22}
{'station': '011990-99999', 'time': 1433273379, 'temp': -11}
{'station': '012650-99999', 'time': 1433275478, 'temp': 111}
我可以看到输出文件中的架构在两个版本之间是不同的:
指定logicalType:
"fields": [{"name": "station", "type": "string"}, {"logicalType": "time-millis", "name": "time", "type": "int"}, {"name": "temp", "type": "int"}]
未指定logicalType:
"fields": [{"name": "station", "type": "string"}, {"name": "time", "type": "int"}, {"name": "temp", "type": "int"}]
但这对输出没有影响。
【问题讨论】:
标签: python python-3.x avro fastavro