使用Flink获取DataStream的文件名

6

我有一个使用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文件名称的方法。

提前致谢。


嘿@Roizo,你解决这个问题了吗? - Josh Lemer
1个回答

6
我曾遇到类似的情况,需要知道正在处理的记录的文件名。有些信息在记录内是无法得知的。要求客户更改记录模式不可取。
我找到了一种获取底层源代码的方法。在我的情况下,它是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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接