我具有以下Avro模式:
{
"name": "schema_name",
"type": "record",
"fields" : [
{
"name": "schema",
"type": "string"
},
{
"name": "data",
"type": {
"type": "array",
"items":
{
"name": "data",
"type": "record",
"fields": [
{
"name": "phone_number",
"type": "string"
}
]
}
}
},
{
"name":"flag",
"type":"string"
}
]
}
我正在使用它从文本文件生成Avro消息:
def main(args: Array[String]): Unit = {
val avroSchemaStr = Source.fromFile("avro_schema.txt").mkString
val avroSchema = new Schema.Parser().parse(avroSchemaStr)
Source.fromFile("phone_numbers.txt").getLines.foreach { msg =>
println(fixedWidthToAvro(msg, avroSchema))
}
}
def fixedWidthToAvro(record: String, avroSchema: Schema): GenericRecord = {
val childSchema = new GenericData.Record(avroSchema).getSchema.getField("data").schema.getElementType
val parentRrecord = new GenericData.Record(avroSchema)
val childRecord = new GenericData.Record(childSchema)
childRecord.put("phone_number", "1234567890")
parentRrecord.put("schema", "schema_name")
parentRrecord.put("data", childRecord)
parentRrecord.put("flag", "I")
println(parentRrecord)
parentRrecord
}
一切正常,对于给定的消息,我得到以下输出:
{"schema": "schema_name", "data": {"phone_number": "1234567890"}, "flag": "I"}
但是,正如我将data
字段类型声明为array
一样,我期望它像集合一样被包裹在方括号中。像这样:
{"schema": "schema_name", "data": [{"phone_number": "1234567890"}], "flag": "I"}
我希望将data
归档文件放在方括号中。我该如何实现?
答案 0 :(得分:1)
记录中有两个元素,名称为data
。一个是数组,另一个是该数组中的元素名称,我认为这就是让您感到困惑的地方。
将schema.getElementType
传递给Record
时,您正在生成一条记录,而忽略了创建Array[Record]
来保存所有这些记录的情况。
您需要的是一个可以记录所有记录的数组:
val avroSchema = new Schema.Parser().parse(schema)
val childSchema = new GenericData.Record(avroSchema).getSchema.getField("data").schema
val parentRecord = new GenericData.Record(avroSchema)
val childRecords = new GenericData.Array[GenericData.Record](1024, childSchema)
val childRecord = new GenericData.Record(childSchema.getElementType)
childRecord.put("phone_number", "33333")
childRecords.add(childRecord)
parentRecord.put("schema", "schema_name")
parentRecord.put("data", childRecords)
parentRecord.put("flag", "I")
println(parentRecord)
收益:
{"schema": "schema_name", "data": [{"phone_number": "33333"}], "flag": "I"}