scala - 使用Flink获取DataStream的文件名

标签 scala streaming apache-flink flink-streaming data-stream

我有一个流处理,其中 flink 在单个路径中处理 csv 文件。 我想知道每个已处理文件的文件名。

我目前正在使用此函数将 csv 文件读入路径(dataPath)。

val recs:DataStream[CallCenterEvent] = env
          .readFile[CallCenterEvent](
          CsvReader.getReaderFormat[CallCenterEvent](dataPath, c._2),
          dataPath,
          FileProcessingMode.PROCESS_CONTINUOUSLY,
          c._2.fileInterval)
          .uid("source-%s-%s".format(systemConfig.name, c._1))
          .name("%s records reading".format(c._1))

并使用该函数获取TupleCsvInputFormat。

def getReaderFormat[T <: Product : ClassTag : TypeInformation](dataPath:String, conf:URMConfiguration): TupleCsvInputFormat[T] = {
  val typeInfo = implicitly[TypeInformation[T]]
  val format: TupleCsvInputFormat[T] = new TupleCsvInputFormat[T](new Path(dataPath), typeInfo.asInstanceOf[CaseClassTypeInfo[T]])
  if (conf.quoteCharacter != null && !conf.quoteCharacter.equals(""))
    format.enableQuotedStringParsing(conf.quoteCharacter.charAt(0))
  format.setFieldDelimiter(conf.fieldDelimiter)
  format.setSkipFirstLineAsHeader(conf.ignoreFirstLine)
  format.setLenient(true)

  return format
}       

该过程运行正常,但我找不到方法来获取每个已处理的 csv 文件的文件名。

提前致谢

最佳答案

我遇到了类似的情况,我需要知道正在处理的记录的文件名。文件名中有一些信息在记录内不可用。要求客户更改记录架构不是一种选择。

我找到了一种访问底层源代码的方法。就我而言,它是 FileInputSplit (其中包含源数据文件的路径信息)

class MyTextInputFormat(p:Path ) extends TextInputFormat(p) {

     override def readRecord(reusable: String, bytes: Array[Byte], offset: Int, numBytes: Int):String = {
val fileName = {
      if (this.currentSplit != null)      
        this.currentSplit.getPath.getName
      else
         "unknown-file-path"
    }

    //Add FileName to the record!
    super.readRecord(reusable, bytes, offset, numBytes)+","+fileName
  }
}

现在,您可以在流设置中使用它

val format = new MyTextInputFormat(new Path(srcDir))
format.setDelimiter(prfl.lineSep)
val stream = env.readFile(format, srcDir, FileProcessingMode.PROCESS_CONTINUOUSLY, Time.seconds(10).toMilliseconds

虽然我的情况略有不同,但这种方法应该对您也有帮助!

关于scala - 使用Flink获取DataStream的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46671411/

相关文章:

Scala:读取并保存 Iterable 的所有元素

mongodb - 无法将数组从 MongoDB 传递到需要向量的 Spark 机器学习函数

azure - 将 Azure Functions 与事件中心链集成的最佳参数是什么

java - 使用具有可变元组大小的 JDBCInputFormat (apache-flink)

java - 如何在 Flink 中连接两个流并进行操作?

java - Scala - 如何在运行时保证 val 不变性

scala - Spark 1.6.1 : Task not serializable when evaluating a classifier on a DataFrame

c# - 从经过身份验证的 URL 传输音频

javascript - NodeJS + Websockets + HTML5 视频标签和 'streaming'

java - Flink Java API - Pojo 类型到元组数据类型