Avro Java API时间戳逻辑类型?

时间:2017-03-28 22:12:58

标签: java time avro

使用Avro Java API,我可以创建一个简单的记录模式,如:

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp").type().longType().noDefault()
            .endRecord();

如何使用逻辑类型标记架构字段,具体如下: https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro/LogicalTypes.TimestampMillis.html

3 个答案:

答案 0 :(得分:11)

感谢DontPanic:

    Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp_with_logical_type").type(timestampMilliType).noDefault()
            .name("timestamp_no_logical_type").type().longType().noDefault()
            .endRecord();

    System.out.println(schemaWithTimestamp.toString(true));

这导致:

{
  "type" : "record",
  "name" : "MyRecord",
  "namespace" : "org.demo",
  "fields" : [ {
    "name" : "timestamp_with_logical_type",
    "type" : {
      "type" : "long",
      "logicalType" : "timestamp-millis"
    }
  }, {
    "name" : "timestamp_no_logical_type",
    "type" : "long"
  } ]
}

答案 1 :(得分:2)

我认为您可以手动创建架构:

live == false

你的架构:

List<Schema.Field> fields = new ArrayList<>();
Schema timeStampField = Schema.create(Schema.Type.LONG);
fields.add(new Schema.Field("timestamp", LogicalTypes.timestampMillis().addToSchema(timeStampField), null, null));
Schema resultSchema = Schema.createRecord("MyRecord", null, "org.demo", false, fields);
System.out.println(resultSchema);

resultSchema with timestampMillis:

{"type":"record","name":"MyRecord","namespace":"org.demo","fields":[{"name":"timestamp","type":"long"}]}

答案 2 :(得分:0)

感谢第一个解决方案,现在提供了可为null的逻辑类型,例如:

{ 
"name":"maturityDate",
  "type":["null", {
    "type":"long","logicalType":"timestamp-millis"
    }]
},

我认为:

        Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

        Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier")
                .namespace("com.baeldung.avro")
                .fields()
                .requiredString("hostName")
                .requiredString("ipAddress")
                .name("maturityDate")
                .type()
                .unionOf()
                .nullType()
                .and()
                .type(timestampMilliType)
                .endUnion()
                .noDefault()
                .endRecord();