iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
1
AI & Data

資料工程師修煉之路系列 第 16

[Day 16] Encoding and Evolution(4) - Avro

接續 Day 15

Avro

最後一個要來談的 binary encoding 方式是 Apache Avro ,閞始於 Hadoop 底下的子專案,它很明顯的跟 Thrift 和 Protocol Buffers 不同,Avro 一樣需要 schema 來定義欄位,Avro 能用 2 個 schema 語言,一個 (Avro IDL - Interface description language) 比較適合人讀,另一個 JSON 版本比較適合機器讀,我們一樣拿這份 JSON 資料來看看 Avro 的 2 種 schema 長什麼樣子,

{
    "userName": "Martin",
    "favoriteNumber": 1337,
    "interests": ["daydreaming", "hacking"]
}

首先是 Avro IDL:

record Person {
	string userName;
	union { null, long } favoriteNumber = null; 
	array<string> interests;
}

再來是 JSON 版 schema:

{
  "type": "record",
  "name": "Person",
  "fields": [
    {
      "name": "userName",
      "type": "string"
    },
    {
      "name": "favoriteNumber",
      "type": [
        "null",
        "long"
      ],
      "default": null
    },
    {
      "name": "interests",
      "type": {
        "type": "array",
        "items": "string"
      }
    }
  ]
}

這裡可以看到,Avro 沒有在 schema 中使用 欄位標籤 (field tags),它 encoding 後的檔案大小是最強大的 32 位元組,encoding 結果細節如下圖:

figure_4-5

Avro 沒有欄位標籤 (field tags) ,也沒有欄位型態,上面只看到說 長度 為何,然後後面就直接接資料了,所以同樣長度下你可以是數字或其他東西,然後 Avro 的數字也是用可變動長度儲存,這點跟 Thrift 和 Protocol Buffers 一樣,

既然沒有欄位標籤跟型態,所以我們如何跟 schema 做對應呢?我們只能用欄位 排序 告知 Avro 每個欄位的資料型態是什麼,也就是說在 decoding 資料時,必須使用 與寫資料時相同的 schema ,任何不匹配的欄位都會造成 decoding 時不正確。

那我們怎麼用 Avro 做 schema 演進 (向前、向後兼容) 呢?就明天講吧!


上一篇
[Day 15] Encoding and Evolution(3) - Thrift and Protocol Buffers
下一篇
[Day 17] Encoding and Evolution (4-2) - Avro Evolution
系列文
資料工程師修煉之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言