我试图在Avro中使用逻辑类型,使用Python 库来读写,但是logicalType注释似乎没有任何效果。下面的代码是从页面中提取的;我修改了模式定义中的time字段,根据当前Avro规范用逻辑类型time-millis对其进行了注释。(顺便提一句,我见过人们使用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)对于stdout的输出,无论是否存在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"}]但是这在输出上并没有什么区别。
发布于 2020-03-25 17:17:38
好的,答案是类型规范本身必须被视为一个模式,所以语法是不同的。在上面的示例中,模式应该定义如下:
模式={“doc”:“天气读物”、“名称”、“命名空间”:“测试”、“类型”:“记录”、“字段”:{“名称”:“站点”、“类型”:“字符串”}、{“名称”:“时间”、“类型”:{“type”:“int”、“logicalType”:“time-millis”},{'name':'temp','type':'int'},
https://stackoverflow.com/questions/60842607
复制相似问题