【问题标题】:use of "default" in avro schema在 avro 模式中使用“默认”
【发布时间】:2018-02-26 09:59:50
【问题描述】:

根据Avro docs 中“default”属性的定义:“此字段的默认值,在读取缺少此字段的实例时使用(可选)。”

这意味着如果缺少对应的字段,则采用默认值。

但情况似乎并非如此。考虑以下student 架构:

{
        "type": "record",
        "namespace": "com.example",
        "name": "Student",
        "fields": [{
                "name": "age",
                "type": "int",
                "default": -1
            },
            {
                "name": "name",
                "type": "string",
                "default": "null"
            }
        ]
    }

Schema 表示:如果缺少“age”字段,则将 value 视为 -1。 “名称”字段也是如此。

现在,如果我尝试从以下 JSON 构建学生模型:

{"age":70}

我得到了这个例外:

org.apache.avro.AvroTypeException: Expected string. Got END_OBJECT

    at org.apache.avro.io.JsonDecoder.error(JsonDecoder.java:698)
    at org.apache.avro.io.JsonDecoder.readString(JsonDecoder.java:227)

默认设置似乎没有按预期工作。那么,这里默认的作用到底是什么?

这是用于生成学生模型的代码:

Decoder decoder = DecoderFactory.get().jsonDecoder(Student.SCHEMA$, studentJson);
SpecificDatumReader<Student> datumReader = new SpecificDatumReader<>(Student.class);
return datumReader.read(null, decoder);

(Student 类由 Avro 编译器从学生模式自动生成)

【问题讨论】:

  • Avro field default values的可能重复
  • @Generic 差别不大。那里的模型是使用构建器构建的并具有默认工作。虽然只有在解析 Json 字符串时才会失败。很少有文章指出字段不能丢失,我觉得这是不合理的。如果我们必须有字段,那么我不明白默认属性会有什么帮助。

标签: java hadoop serialization apache-kafka avro


【解决方案1】:

我认为对默认值有一些误解,所以希望我的解释也能对其他人有所帮助。当字段不存在时,默认值对于提供默认值很有用,但这本质上是当您实例化一个 avro 对象(在您的情况下调用datumReader.read)但它不允许读取具有不同模式的数据时,这这就是为什么“模式注册表”的概念对这种情况有用的原因。

以下代码有效并允许读取您的数据

Decoder decoder = DecoderFactory.get().jsonDecoder(Student.SCHEMA$, "{\"age\":70}");
SpecificDatumReader<Student> datumReader = new SpecificDatumReader<>(Student.class);

Schema expected = new Schema.Parser().parse("{\n" +
        "  \"type\": \"record\",\n" +
        "  \"namespace\": \"com.example\",\n" +
        "  \"name\": \"Student\",\n" +
        "  \"fields\": [{\n" +
        "    \"name\": \"age\",\n" +
        "    \"type\": \"int\",\n" +
        "    \"default\": -1\n" +
        "  }\n" +
        "  ]\n" +
        "}");

datumReader.setSchema(expected);
System.out.println(datumReader.read(null, decoder));

如您所见,我指定了用于“写入”不包含字段“名称”的 json 输入的架构,但是(考虑到您的架构包含默认值)当您打印记录时,您将看到使用默认值命名

{"age": 70, "name": "null"}

以防万一,可能或可能不知道,“null”并不是真正的空值,而是一个值为“null”的字符串。

【讨论】:

  • datumReader.setSchema(expected) 适用于缺少的字段。但不幸的是,当输入 json 确实包含“name”字段时,它仍然将值设置为“null”。即如果输入是{"age": 70, "name": "john"},我将得到名称设置为“null”的学生模型。我期望将其设置为“约翰”。没有其他方法可以解决这些缺失的字段吗??
  • 2 个选项。将编写器模式作为消息的一部分发送(昂贵)或使用模式注册表
【解决方案2】:

只是添加上面答案中已经说过的内容。为了使字段在不存在时为空。然后将其类型与 null 联合。否则它只是一个拼写为 null 的字符串,它会进入.example 模式:

{
"name": "name",
"type": [
  "null",
  "string"
],
"default": null

}

然后如果您添加{"age":70} 并检索记录,您将得到以下信息:

{"age":70,"name":null}

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多