本文整理汇总了Scala中org.apache.avro.generic.IndexedRecord类的典型用法代码示例。如果您正苦于以下问题:Scala IndexedRecord类的具体用法?Scala IndexedRecord怎么用?Scala IndexedRecord使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IndexedRecord类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: get
//设置package包名称以及导入依赖的类
package com.datamountaineer.avro.kcql
import com.datamountaineer.avro.kcql.AvroKcql._
import com.datamountaineer.avro.kcql.AvroSchemaKcql._
import org.apache.avro.Schema
import org.apache.avro.generic.IndexedRecord
import org.apache.avro.util.Utf8
trait AvroFieldValueGetter {
def get(value: Any, schema: Schema, path: Seq[String]): Option[Any] = {
path.headOption.map { parent =>
schema.getType match {
case Schema.Type.RECORD => if (Option(value).isEmpty) None else fromRecord(value, schema, path)
case Schema.Type.MAP => if (Option(value).isEmpty) None else fromMap(value, schema, path)
case Schema.Type.UNION => get(value, schema.fromUnion(), path)
case _ => throw new IllegalArgumentException(s"Can't select $parent field from schema:$schema")
}
}.getOrElse {
schema.getType match {
case Schema.Type.BOOLEAN | Schema.Type.NULL |
Schema.Type.DOUBLE | Schema.Type.FLOAT |
Schema.Type.LONG | Schema.Type.INT |
Schema.Type.ENUM | Schema.Type.BYTES |
Schema.Type.FIXED => Option(value)
case Schema.Type.STRING => Option(new Utf8(value.toString).asInstanceOf[Any]) //yes UTF8
case Schema.Type.UNION => get(value, schema.fromUnion(), path)
case Schema.Type.ARRAY | Schema.Type.MAP | Schema.Type.RECORD =>
throw new IllegalArgumentException(s"Can't select an element from an array(schema:$schema)")
case other => throw new IllegalArgumentException(s"Invalid Avro schema type:$other")
}
}
}
private def fromRecord(value: Any, schema: Schema, path: Seq[String]) = {
val field = Option(schema.getField(path.head))
.getOrElse(throw new IllegalArgumentException(s"Can't find field:${path.head} in schema:$schema"))
val v = value.asInstanceOf[IndexedRecord].get(path.head)
get(v, field.schema(), path.tail)
}
private def fromMap(value: Any, schema: Schema, path: Seq[String]) = {
val field = Option(schema.getField(path.head))
.getOrElse(throw new IllegalArgumentException(s"Can't find field:${path.head} in schema:$schema"))
val v = value.asInstanceOf[IndexedRecord].get(path.head)
get(v, field.schema(), path.tail)
}
}