Search code examples
avro

What is the correct Avro schema for Union type of null or UUID


I am trying to define an Avro schema for an optional nullable GUID. Is it correct to put a logicalType as part of a union type like this?

I've looked in the docs and can't find an example for this use case

{
  "name": "MyMessageType",
  "type": "record",
  "namespace": "com.mycompany.kafka.records",
  "fields": [
    {
      "name": "userId",
      "type": [
        "null",
        {
          "type": "string",
          "logicalType": "uuid"
        }
      ],
      "default": null,
    },
    { ... more fields ... }
  ]
}

Solution

  • The correct way is as you wrote, the logical type is part of the type definition and not part of the union definition.

    e.g. Right way:

      "type": [
        "null",
        {
          "type": "string",
          "logicalType": "uuid" //Logical type is part of the 'string' type definition
        }
      ],
    

    and not as part of the union definition.

    e.g. Wrong way

      "logicalType": "uuid" //Wrong way - Logical type is NOT part of the 'union' type definition
      "type": [
        "null",
        {
          "type": "string",
        }
      ],
    

    BTW, you can have union which defines several different logical types, and this may be the reason why the logical type is part of the union branch and not part of the entire union.