如何为包含多记录类型的数组创建Avro Schema?
为你的多对象数组JSON构建Avro Schema
没问题!我来帮你搞定这个Avro Schema的定义,特别是里面的两种数组类型——简单字符串数组和复杂对象数组,Avro都有清晰的语法来处理。
先看你给出的JSON payload结构:
{
"id": "channel-id",
"name": "My Channel with a New Title",
"description": "Herpy me derpy merpus herpsum ner berp berps derp ter tee",
"privacyLevel": "<private|org>",
"planId": "some-plan-id",
"owner": "a-user-handle",
"curators": [ "user-handle-1", "user-handle-2" ],
"members": 5,
"content": [ { "id": "content-id-1" } ]
}
对应的Avro Schema可以这么写:
{ "type": "record", "name": "Channel", "namespace": "com.example", // 可替换为你自己的命名空间 "fields": [ {"name": "id", "type": "string"}, {"name": "name", "type": "string"}, {"name": "description", "type": "string"}, {"name": "privacyLevel", "type": ["null", "string"], "default": null}, // 也可以用枚举优化,下文说明 {"name": "planId", "type": ["null", "string"], "default": null}, {"name": "owner", "type": "string"}, {"name": "curators", "type": {"type": "array", "items": "string"}, "default": []}, {"name": "members", "type": ["null", "int"], "default": null}, {"name": "content", "type": {"type": "array", "items": { "type": "record", "name": "ContentItem", "fields": [ {"name": "id", "type": "string"} // 可补充content对象的其他字段,比如title、createTime等 ] }}, "default": []} ] }
关键部分解释:
- 简单数组(curators):直接用
{"type": "array", "items": "string"}定义,items指定数组元素为字符串类型,同时设置默认空数组,避免空值解析问题。 - 复杂对象数组(content):数组的
items是嵌套的record类型(这里命名为ContentItem),你可以在这个子record里定义content对象的所有属性,后续有新增字段直接添加到fields数组即可。 - 可选字段与默认值:给部分字段设置了
["null", "类型"]的联合类型,并添加default: null,让这些字段支持空值,更贴合实际业务场景;如果是必填字段,直接写单一类型即可(比如id、name、owner)。 - 枚举类型优化(privacyLevel):由于你的
privacyLevel只有private和org两个可选值,用枚举类型会更严谨,替换成下面的写法即可:{"name": "privacyLevel", "type": { "type": "enum", "name": "PrivacyLevel", "symbols": ["private", "org"] }}
这样定义的Schema就能完美匹配你的JSON结构,不管是简单数组还是嵌套对象数组都能正确解析啦。
内容的提问来源于stack exchange,提问作者flybonzai
相关产品推荐
相关产品推荐

