Java Avro 字段默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22938124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Avro field default values
提问by Kesh
I am running into some issues setting up default values for Avro fields. I have a simple schema as given below:
我在为 Avro 字段设置默认值时遇到了一些问题。我有一个简单的架构,如下所示:
data.avsc:
数据.avsc:
{
"namespace":"test",
"type":"record",
"name":"Data",
"fields":[
{ "name": "id", "type": [ "long", "null" ] },
{ "name": "value", "type": [ "string", "null" ] },
{ "name": "raw", "type": [ "bytes", "null" ] }
]
}
I am using the avro-maven-plugin v1.7.6to generate the Java model.
我正在使用avro-maven-plugin v1.7.6来生成 Java 模型。
When I create an instance of the model using:
Data data = Data.newBuilder().build();
, it fails with an exception:
当我使用: 创建模型的实例时
Data data = Data.newBuilder().build();
,它失败并出现异常:
org.apache.avro.AvroRuntimeException: org.apache.avro.AvroRuntimeException: Field id type:UNION pos:0 not set and has no default value.
org.apache.avro.AvroRuntimeException: org.apache.avro.AvroRuntimeException: 字段 ID 类型:UNION pos:0 未设置且没有默认值。
But if I specify the "default" property,
但是如果我指定“默认”属性,
{ "name": "id", "type": [ "long", "null" ], "default": "null" },
I do not get this error. I read in the documentation that first schema in the union becomes the default schema. So my question is, why do I still need to specify the "default" property? How else do I make a field optional?
我没有收到这个错误。我在文档中读到联合中的第一个架构成为默认架构。所以我的问题是,为什么我仍然需要指定“默认”属性?我如何使字段可选?
And if I do need to specify the default values, how does that work for a union; do I need to specify default values for each schema in the union and how does that work in terms of order/syntax?
如果我确实需要指定默认值,这对联合如何工作;我是否需要为联合中的每个模式指定默认值以及它在顺序/语法方面是如何工作的?
Thanks.
谢谢。
采纳答案by Y.H.
The default value of a union corresponds to the first schema of the union (Source). Your union is defined as ["long", "null"]
therefor the default value must be a long number. null
is not a long number that is why you are getting an error.
联合的默认值对应于联合的第一个模式 ( Source)。您的联合被定义为["long", "null"]
因此默认值必须是一个长数字。null
不是一个很长的数字,这就是您收到错误的原因。
If you still want to define null
as a default value then put null schema first, i.e. change the union to ["null", "long"]
instead.
如果您仍想定义null
为默认值,则首先放置空模式,即将联合更改为["null", "long"]
。
回答by Rites
回答by blueberry
You must provide "default": null
not "default": "null"
in the schema to get the builder method working
您必须在架构中提供"default": null
not"default": "null"
才能使构建器方法正常工作