Avro使用不存在的架构字段附加通用记录

时间:2017-02-20 12:55:02

标签: java avro

我有以下架构

{"namespace": "POS.avro",
 "type": "record",
 "name": "POS",
 "fields": [
     {"name": "TransactionID", "type": "int"},
     {"name": "Date", "type": "long"},
     {"name": "Invoice", "type": "string"},
     {"name": "StoreId", "type": "string"},
     {"name": "StoreName", "type": "string"},
     {"name": "SalesMan", "type": "string"},
  ]
}

我在Java中创建通用记录以将其附加到Avro文件

    DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
    File avroFile = new File(avroFileName);

    DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
    dataFileWriter.create(schema, avroFile);

    // Instantiating the GenericRecord class.
    GenericRecord salesRecord = new GenericData.Record(schema);

    String key = "Product Name";
    Field field = schema.getField(key);
    if (field == null) {
        salesRecord.put(key, "some value");
    }

    dataFileWriter.append(salesRecord);

我正在尝试追加不存在的字段,但要获得AvroRuntimeException。

我们可以追加不存在的字段吗?如果是,使用Java附加此类字段的方法是什么?

1 个答案:

答案 0 :(得分:0)

如果架构中没有字段,则不能在genericRecord中放置任何键值。

这就是put方法的工作原理:

public void put(String key, Object value) {
    Field field = this.schema.getField(key);
    if(field == null) {
        throw new AvroRuntimeException("Not a valid schema field: " + key);
    } else {
        this.values[field.pos()] = value;
    }
}

PS。您确定您的架构有效吗?第{"name": "SalesMan", "type": "string"},

中有额外的逗号