2017-05-05 131 views
0

我正在使用apache avro并希望从我的模式中获取逻辑类型。我尝试使用函数getLogicalType(),但它返回null。我不明白什么是错的。我的模式如下。apache avro api的getLogicalType()函数即使存在也会返回null

{ 
    "namespace": "example.avro", 
    "type": "record", 
    "name": "User", 
    "fields": [ 
     {"name": "name", "type": "string"}, 
     {"name": "favorite_number", "type": "int", "logicalType": "decimal", "precision": 2, "scale": "2"}, 
     {"name": "favorite_color", "type": ["string", "null"]} 
    ] 
} 

以下是我在哪里访问logicalType

for(Schema.Field currField : schema.getFields()) { 

     field = createFieldList(currField.name(), currField.schema().getType().toString(), currField.schema().getLogicalType()); 
     fields.add(field); 
    } 
+0

正如我在评论中写道,以我的回答你有为所有字段循环,并且只为第二个字段定义* logicalType *,这就是为什么getLogicalType()返回null,至少对于第一个和第三个字段。尝试仅为每个字段输出getLogicalType的结果,而不是在createFieldList()中使用它。 – LLL

+0

不,它打印全部为空 – Hazzard

回答

0

伙计们,我想我找到了答案。逻辑类型被声明的方式是错误的。取而代之的

{ 
    "name": "favorite_number", 
    "type": "int", 
    "logicalType": "decimal", 
    "precision": 2, 
    "scale": "2" 
}, 

应该

{ 
    "name": "favorite_number", 
    "type": { 
    "type": "int", 
    "logicalType": "decimal", 
    "precision": 2, 
    "scale": "2" 
    } 
}, 

现在,当我使用getlogicalType()函数,它给了我预期的结果

+0

如果这是解决方案,那么我认为你应该得到SchemaParseException,因为你写了你没有得到它,我认为这可能是一个错误。无论如何,它很适合你。 – LLL

+1

顺便说一句,您可以通过使用函数getObjectProps()在第一个实例中访问logicalType。它返回一个地图,您可以从中访问一个字段的所有属性。至于它是否应该抛出异常,我真的不知道它是否应该。谢谢你的帮助。 – Hazzard

0

您需要使用解析方法将设置logicalType heresetLogicalType将初始化here的代码。我没有经历过这个图书馆,但基于代码我没有看到其他方式。

然后这个变量将由getLogicalType返回您正在使用的方法。

+0

我使用了解析方法。然后我试图访问这些字段并尝试获取逻辑类型。但它返回null。 currField.schema()。getLogicalType()。这里currField的类型是Field – Hazzard

+0

您是否抓住并忽略了例如SchemaParseException? – LLL

+0

Err。为什么会抛出这个例外。上面的模式被解析。 – Hazzard

相关问题