模式匹配和RDD

时间:2016-03-21 11:22:40

标签: scala apache-spark pattern-matching rdd

我有一个非常简单(n00b)的问题,但我不知何故被卡住了。我尝试使用<div ng-controller="ExampleController"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <code>{{template.url}}</code> <hr/> <div class="slide-animate-container"> <div class="slide-animate" ng-include="template.url"></div> </div> </div> 在Spark中读取一组文件,并希望返回wholeTextFiles,其中RDD[LogEntry]只是一个案例类。我想最终得到一个有效条目的RDD,我需要使用正则表达式来提取我的case类的参数。当条目无效时,我不希望提取器逻辑失败,只需在日志中写入条目。为此,我使用LazyLogging。

LogEntry

这给了我一个object LogProcessors extends LazyLogging { def extractLogs(sc: SparkContext, path: String, numPartitions: Int = 5): RDD[Option[CleaningLogEntry]] = { val pattern = "<some pattern>".r val logs = sc.wholeTextFiles(path, numPartitions) val entries = logs.map(fileContent => { val file = fileContent._1 val content = fileContent._2 content.split("\\r?\\n").map(line => line match { case pattern(dt, ev, seq) => Some(LogEntry(<...>)) case _ => logger.error(s"Cannot parse $file: $line"); None }) }) 。是否有一种巧妙的方式来结束RDD[Array[Option[LogEntry]]]的RDD?我不知何故错过了它。

我正在考虑使用LogEntry,但我不确定这是否更好。

非常感谢。

1 个答案:

答案 0 :(得分:2)

  1. 要摆脱Array - 只需将map命令替换为flatMap - flatMap会将每个记录的类型Traversable[T]的结果视为单独的类型为T的记录。

  2. 要删除Option - collect只有成功的entries.collect { case Some(entry) => entry }。 请注意,此collect(p: PartialFunction)重载(执行与mapfilter相同的内容)与collect()(将所有数据发送给驱动程序)非常不同。 / p>

  3. 总而言之,这就像是:

    def extractLogs(sc: SparkContext, path: String, numPartitions: Int = 5): RDD[CleaningLogEntry] = {
    
      val pattern = "<some pattern>".r
    
      val logs = sc.wholeTextFiles(path, numPartitions)
      val entries = logs.flatMap(fileContent => {
        val file = fileContent._1
        val content = fileContent._2
        content.split("\\r?\\n").map(line => line match {
          case pattern(dt, ev, seq) => Some(LogEntry(<...>))
          case _ => logger.error(s"Cannot parse $file: $line"); None
        })
      })
    
      entries.collect { case Some(entry) => entry }
    }
    
相关问题