简体   繁体   中英

How can I get Avro SchemaBuilder to build a schema of a map between two 'records'?

Trying to serialize Java Objects represented as a Map. This requires me to build an Avro Schema first. I am using Avro SchemaBuilder for schema generation. Have already succeeded in schema generation for Map's objects. However can't deal with schema building for overall Map. Final schema should look like the following (created this one manually):

{
    "type": "record",
    "name": "MapObject",
    "namespace": "test",
    "fields": [
        {
            "name": "CacheMap",
            "type": {
                "type": "map",
                "values": [
                    {
                        "type": "record",
                        "name": "User",
                        "namespace": "test",
                        "fields": [                         
                            {
                                "name": "id",
                                "type": "long"
                            },
                            {
                                "name": "status",
                                "type": "string"
                            }
                        ]
                    },
                    {
                        "type": "record",
                        "name": "UserKey",
                        "namespace": "test",
                        "fields": [
                            {
                                "name": "key",
                                "type": "long"
                            },
                            {
                                "name": "keyPrint",
                                "type": "string"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}

How can I pass to different records for key and value of a map in SchemaBuilder? SchemaBuilder.map().values() does not allow to pass more than one Schema as a parameter for .value() .

Apache Avro Unions can be of help here.

SchemaBuilder.builder()
            .map()
 .values(SchemaBuilder.unionOf().type(firstSchema).and().type(secondSchema).endUnion());

where the firstSchema and the secondSchema are separate schemas already defined for required User and UserKey 'records' (considering the schema from question)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM