[英]How do I define a complex type in an Avro Schema
我已經查看了avro文檔以及一些在線示例(以及類似的StackOverflow問題)。 然后,我嘗試定義avro模式,並且必須逐步退出字段以確定我的問題所在(來自python中的avro庫的錯誤消息沒有人們希望的那樣有用)。 我有一個要轉換為Avro的JSON文檔,我需要為此指定一個模式(使用avro-tools從json生成模式無法按預期工作,並在嘗試轉換為時產生了AvroTypeException json轉換為avro)。 我正在使用Avro版本1.7.7。 這是我要為其定義avro模式的JSON文檔:
{
"method": "Do_Thing",
"code": 200,
"reason": "OK",
"siteId": {
"string": "a1283632-121a-4a3f-9560-7b73830f94j8"
}
}
我能夠為非復雜類型定義模式,但不能為復雜的“ siteId”字段定義模式:
{
"namespace" : "com.example",
"name" : "methodEvent",
"type" : "record",
"fields" : [
{"name": "method", "type": "string"},
{"name": "code", "type": "int"},
{"name": "reason", "type": "string"}
{"name": "siteId", "type": [ "null", "string" ]}
]
}
嘗試使用以前的架構將Json對象轉換為avro會產生avro.io.AvroTypeException:數據[參見上述JSON對象]不是該架構的示例[請參見上述Avro架構對象]。 我只在嘗試在架構中定義一個字段來表示上述json中的“ siteId”字段時才看到此錯誤。
Avro的python實現表示的聯合與JSON編碼不同:它“解包”聯合,因此siteId
字段應該只是字符串,沒有包裝對象。 請參見下面的一些示例。
非null siteid
:
{
"method": "Do_Thing",
"code": 200,
"reason": "OK",
"siteId": {
"string": "a1283632-121a-4a3f-9560-7b73830f94j8"
}
}
空siteid
:
{
"method": "Do_Thing",
"code": 200,
"reason": "OK",
"siteId": null
}
非null siteid
:
{
"method": "Do_Thing",
"code": 200,
"reason": "OK",
"siteId": "a1283632-121a-4a3f-9560-7b73830f94j8"
}
空siteid
:
{
"method": "Do_Thing",
"code": 200,
"reason": "OK",
"siteId": null
}
請注意,在兩種情況下都將null
展開 ,這就是您的解決方案無法正常工作的原因。
不幸的是,python實現當前沒有JSON解碼器/編碼器(AFAIK),因此沒有簡單的方法可以在兩種表示形式之間進行轉換。 根據您的JSON編碼數據的來源,最簡單的方法可能是對其進行編輯以不再包裝聯合實例。
我可以使用以下架構解決問題:
{
"namespace" : "com.example",
"name" : "methodEvent",
"type" : "record",
"fields" : [
{"name": "method", "type": "string"},
{"name": "code", "type": "int"},
{"name": "reason", "type": "string"}
{
"name": "siteId",
"type": {
"name" : "siteId",
"type" : "record",
"fields" : [
"name" : "string",
"type" : [ "null", "string" ]
]
}
},
"default" : null
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.