2016-03-16 55 views
0

的Avro架構假設我有以下JSON:的JSON數組

[ 
    {"id":1,"text":"some text","user_id":1}, 
    {"id":1,"text":"some text","user_id":2}, 
    ... 
] 

什麼將是這個數組對象的適當的Avro的模式?

回答

1

[簡答]
該數組對象的合適的Avro模式會是什麼樣子:

const type = avro.Type.forSchema({ 
    type: 'array', 
    items: { type: 'record', fields: 
    [ { name: 'id', type: 'int' }, 
    { name: 'text', type: 'string' }, 
    { name: 'user_id', type: 'int' } ] 
    } 
}); 

[長的答案]
我們可以用Avro公司來幫助我們建立以上給定的數據對象的模式。
讓我們使用npm包「avsc」,這是「Avro規範的純JavaScript實現」。
由於Avro可以推斷出值的模式,我們可以使用以下技巧通過給定的數據來獲取模式(不幸的是,它似乎不能顯示嵌套的模式,但我們可以問兩次 - 頂級結構(數組),然後數組元素) :

// don't forget to install avsc 
// npm install avsc 
// 
const avro = require('avsc'); 

// avro can infer a value's schema 
const type = avro.Type.forValue([ 
    {"id":1,"text":"some text","user_id":1} 
]); 

const type2 = avro.Type.forValue(
    {"id":1,"text":"some text","user_id":1} 
); 


console.log(type.getSchema()); 
console.log(type2.getSchema()); 

輸出:

{ type: 'array', 
    items: { type: 'record', fields: [ [Object], [Object], [Object] ] } } 
{ type: 'record', 
    fields: 
    [ { name: 'id', type: 'int' }, 
    { name: 'text', type: 'string' }, 
    { name: 'user_id', type: 'int' } ] } 

現在讓我們來撰寫適當的模式,並嘗試用它來序列化對象,然後反序列化它回來了!

const avro = require('avsc'); 
const type = avro.Type.forSchema({ 
    type: 'array', 
    items: { type: 'record', fields: 
    [ { name: 'id', type: 'int' }, 
    { name: 'text', type: 'string' }, 
    { name: 'user_id', type: 'int' } ] 
    } 
}); 
const buf = type.toBuffer([ 
    {"id":1,"text":"some text","user_id":1}, 
    {"id":1,"text":"some text","user_id":2}]); // Encoded buffer. 

const val = type.fromBuffer(buf); 
console.log("deserialized object: ", JSON.stringify(val, null, 4)); // pretty print deserialized result 

var fs = require('fs'); 
var full_filename = "/tmp/avro_buf.dat"; 
fs.writeFile(full_filename, buf, function(err) { 
    if(err) { 
     return console.log(err); 
    } 

    console.log("The file was saved to '" + full_filename + "'"); 
}); 

輸出:

deserialized object: [ 
    { 
     "id": 1, 
     "text": "some text", 
     "user_id": 1 
    }, 
    { 
     "id": 1, 
     "text": "some text", 
     "user_id": 2 
    } 
] 
The file was saved to '/tmp/avro_buf.dat' 

我們甚至可以享受以上運動的緊湊二進制表示:

hexdump -C /tmp/avro_buf.dat 
00000000 04 02 12 73 6f 6d 65 20 74 65 78 74 02 02 12 73 |...some text...s| 
00000010 6f 6d 65 20 74 65 78 74 04 00     |ome text..| 
0000001a 

尼斯,是不是她 - )