【问题标题】:Write nullable item to avro record in Avro C将可为空的项目写入 Avro C 中的 avro 记录
【发布时间】:2018-09-05 15:10:31
【问题描述】:

架构:

const char schema[] = 
    "{ \"type\":\"record\", \"name\":\"foo\","
    "\"fields\": ["
        "{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
    "]}";

设置架构:

avro_datum_t foo_record = avro_record(schema);

设置可空数据:

avro_datum_t nullableint = avro_int32(1);

设置项目:

int err = avro_record_set(foo_record,"nullableint",nullableint);

写项目:

int err2 = avro_file_writer_append(avro_writer, foo_record);

还有一个错误。不知何故,我必须设置我的可为空条目的分支,但我没有看到可以执行此操作的函数。

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

【问题讨论】:

    标签: c avro


    【解决方案1】:

    请看下面的代码,它设置了 union 分支和 int 分支:

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

    #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 以便更好地检查结果。这个程序的输出是

    got json for int branch: {"nullableint": {"int": 100}}
    got json for null branch: {"nullableint": null}
    

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

    "{ \"name\": \"nullableint\", \"type\":[\"null\",\"int\"]}"
    

    不是

    "{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2020-07-20
      • 2015-05-01
      • 2021-11-30
      相关资源
      最近更新 更多