0

我正在尝试在 Avro 中使用逻辑类型,使用 Python fastavro库进行读写,但logicalType注释似乎根本没有效果。下面的代码取自fastavro页面;根据当前的 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"}]

但这对输出没有影响。

4

1 回答 1

0

好的,答案是类型规范本身必须被视为一个模式,所以语法是不同的。在上面的示例中,模式应定义如下:

schema = { 'doc': '天气读数。', 'name': 'Weather', 'namespace': 'test', 'type': 'record', 'fields': [ {'name': 'station ', 'type': 'string'}, {'name': 'time', 'type': {'type': 'int', 'logicalType': 'time-millis'}}, {'name': 'temp', 'type': 'int'}, ],

于 2020-03-25T17:17:38.077 回答