Avro Schema Union类型最简示例及对应JSON数据问询
Avro Union类型字段的Schema与JSON示例
没问题,我来给你梳理清楚Avro里Union类型的两种场景——不含null和允许null值的最简可复用示例:
1. 不含null值的Union类型
比如我们定义一个字段支持**字符串(string)或整数(int)**类型,不需要null值:
最简Schema
{ "type": "record", "name": "SampleRecordNoNull", "fields": [ { "name": "mixed_field", "type": ["string", "int"] } ] }
对应JSON数据示例
- 使用字符串值:
{"mixed_field": "hello avro"}
- 使用整数值:
{"mixed_field": 123}
2. 允许null值的Union类型
如果需要字段可以为null,必须把"null"明确加入Union的类型列表中(通常习惯把null放在首位,不过顺序不影响Avro的解析逻辑):
最简Schema
{ "type": "record", "name": "SampleRecordWithNull", "fields": [ { "name": "nullable_mixed_field", "type": ["null", "string", "int"] } ] }
对应JSON数据示例
- 使用null值:
{"nullable_mixed_field": null}
- 使用字符串值:
{"nullable_mixed_field": "test null support"}
- 使用整数值:
{"nullable_mixed_field": 456}
关键提示
Avro的Union类型是通过数组声明的,每个元素代表一种允许的类型。如果需要字段支持null,"null"必须作为Union的成员之一,不能省略——这是新手常犯的错误,直接在普通类型里写null是不生效的哦。
内容的提问来源于stack exchange,提问作者user9750148
相关产品推荐
相关产品推荐

