【问题标题】:How to read Avro schema from empty RDD?如何从空 RDD 中读取 Avro 模式?
【发布时间】:2017-12-04 15:12:29
【问题描述】:

我正在使用AvroKeyInputFormat 来读取 avro 文件:

val records = sc.newAPIHadoopFile[AvroKey[T], NullWritable, AvroKeyInputFormat[T]](path)
  .map(_._1.datum())

因为我需要在工作中反思架构,所以我得到了这样的 Avro 架构:

val schema = records.first.getSchema

很遗憾,如果 path 中的 avro 文件为空(它们包含 writer 架构,但没有记录),则会失败。

即使没有记录,是否有一种简单的方法可以仅使用 Spark 加载 avro 架构?

【问题讨论】:

    标签: apache-spark avro spark-avro


    【解决方案1】:

    我找到了一个解决方案(灵感来自com.databricks.spark.avro.DefaultSource):

    /**
      * Loads a schema from avro files in `directory`. This method also works if none
      * of the avro files contain any records.
      */
    def schema(directory: String)(implicit sc: SparkContext): Schema = {
      val fs = FileSystem.get(new URI(directory), sc.hadoopConfiguration)
      val it = fs.listFiles(new Path(directory), false)
    
      var avroFile: Option[FileStatus] = None
    
      while (it.hasNext && avroFile.isEmpty) {
        val fileStatus = it.next()
    
        if (fileStatus.isFile && fileStatus.getPath.getName.endsWith(".avro")) {
          avroFile = Some(fileStatus)
        }
      }
    
      avroFile.fold {
        throw new Exception(s"No avro files found in $directory")
      } { file =>
        val in = new FsInput(file.getPath, sc.hadoopConfiguration)
        try {
          val reader = DataFileReader.openReader(in, new GenericDatumReader[GenericRecord]())
          try {
            reader.getSchema
          } finally {
            reader.close()
          }
        } finally {
          in.close()
        }
      }
    }
    

    【讨论】:

    • 如果您可能需要提前获取架构,我正在徘徊。 records.first 是可疑的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2016-04-09
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多