首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在avro C中将可空项写入Avro记录

在avro C中将可空项写入Avro记录
EN

Stack Overflow用户
提问于 2018-09-05 15:10:31
回答 1查看 609关注 0票数 1

模式:

代码语言:javascript
复制
const char schema[] = 
    "{ \"type\":\"record\", \"name\":\"foo\","
    "\"fields\": ["
        "{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
    "]}";

设置架构:

代码语言:javascript
复制
avro_datum_t foo_record = avro_record(schema);

设置可空基准:

代码语言:javascript
复制
avro_datum_t nullableint = avro_int32(1);

设置项目:

代码语言:javascript
复制
int err = avro_record_set(foo_record,"nullableint",nullableint);

写出以下项目:

代码语言:javascript
复制
int err2 = avro_file_writer_append(avro_writer, foo_record);

这是个错误。无论如何,我必须设置我的可空条目的分支,但是我没有看到任何函数可以做到这一点。

如何将此值设置为null或int?

EN

回答 1

Stack Overflow用户

发布于 2018-09-05 15:26:38

请参见设置联合分支和int分支的以下代码:

注意:对于联合,您需要在设置数据之前设置相关分支。联合分支索引从0开始,称为判别。对于本例中的int字段,判别符为0(因为它是第一个字段)。对于空分支,判别符为1(因为它是第二个字段)。将null作为第一个分支更常见,但是,我遵循了您的问题示例。

代码语言:javascript
复制
#include "avro.h"
void main()
{
    const char schema_json[] =
        "{ \"type\":\"record\", \"name\":\"foo\","
        "\"fields\": ["
        "{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
        "]}";
    avro_schema_t my_schema;
    avro_schema_from_json( schema_json, 0, &my_schema, NULL );
    avro_datum_t  my_record = avro_datum_from_schema( my_schema );
    avro_datum_t  my_int_field = NULL;
    avro_datum_t  branch = NULL;
    char  *json = NULL;

    //get the int field
    avro_record_get( my_record, "nullableint", &my_int_field );

    //set the int branch on this field
    avro_union_set_discriminant( my_int_field, 0, &branch );
    //set value of 100 at this int branch
    avro_int32_set( branch, 100 );
    //convert the datum record data to json
    avro_datum_to_json( my_record, 1, &json );
    printf( "got json for int branch: %s\n", json );

    //get the int field
    avro_record_get( my_record, "nullableint", &my_int_field );
    //set the null branch on this field
    avro_union_set_discriminant( my_int_field, 1, &branch );
    //convert the datum record data to json
    avro_datum_to_json( my_record, 1, &json );
    printf( "got json for null branch: %s\n", json );

}

为了更好地检查结果,我把数据打印成json。这个程序的输出是

代码语言:javascript
复制
got json for int branch: {"nullableint": {"int": 100}}
got json for null branch: {"nullableint": null}

顺便说一句,约定是将空分支作为第一个分支,具有

代码语言:javascript
复制
"{ \"name\": \"nullableint\", \"type\":[\"null\",\"int\"]}"

而不是

代码语言:javascript
复制
"{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"

请参阅avro规范中的引文:https://avro.apache.org/docs/1.8.2/spec.html

(注意,当为类型为union的记录字段指定默认值时,默认值的类型必须与联合的第一个元素匹配。因此,对于包含"null“的联合,通常首先列出"null",因为此类联合的默认值通常为null)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52188432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档