Ruby Avro:记录模式报告数据无效

Ruby Avro: Record schema reports datum is not valid

我正在尝试使用 avro 和模式序列化 JSON。这不是一个 rails 应用程序(尽管有标签,但我需要注意),所以我也可以使用地图,但是,以下都不是。

schema = { 'type' => 'record', 'name' => 'test', 'fields' => [ { 'name' => 'field_one', 'type' => 'string' },
                                                               { 'name' => 'field_two', 'type' => 'string'},
                                                               { 'name' => 'field_three', 'type' => 'string'},
                                                               { 'name' => 'field_four', 'type' => 'string' } ] }.to_json
message = {'field_one' => 'why',
             'field_two' => 'this',
             'field_three' => 'no',
             'field_four' => 'worky?'}.to_json
schema = Avro::Schema.parse(schema)
dw = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new()
encoder = Avro::IO::BinaryEncoder.new(buffer)
dw.write(message, encoder)
puts buffer.read


returns: 'The datum ... is not an example of schema ...'

将上面的架构替换为以下内容:

schema = { 'type' => 'map', 'values' => 'string' }.to_json

结果:'undefined method `keys' for StringObject'

不确定,为什么我不能用 string:string key:values 创建一个简单的地图。 Avro 的 ruby 文档很糟糕;实际例子很少,占位符模板很多,留给想象的空间很大。我希望能够将这个序列化的字符串对象放入类型为 application/json 的 http 请求中,这可能是个问题,因为 avro 希望成为二进制文件。

require 'avro'
require 'json'

schema = { 'type' => 'record', 'name' => 'Test', 'fields' => [ { 'name' => 'field_one', 'type' => 'string' },
                                                               { 'name' => 'field_two', 'type' => 'string'},
                                                               { 'name' => 'field_three', 'type' => 'string'},
                                                               { 'name' => 'field_four', 'type' => 'string' } ] }.to_json

message = {'field_one' => 'why',
             'field_two' => 'this',
             'field_three' => 'no',
             'field_four' => 'worky?'}

schema = Avro::Schema.parse(schema)
writer = Avro::IO::DatumWriter.new(schema)
buffer = StringIO.new
writer = Avro::DataFile::Writer.new(buffer, writer, schema)
writer << message
writer.close # important

result = buffer.string

puts result