簡體   English   中英

從文件讀取行應用正則表達式並寫入鑲木地板文件scala spark

[英]Read line from file apply regex and write to parquet file scala spark

嗨,我有一個包含日志事件的日志文件。 我需要讀取行並應用正則表達式以從行中獲取元素並寫入鑲木地板文件。 我有一個具有列定義的avro模式。

有人可以指導我繼續這一步嗎?

val spark = SparkSession
  .builder()
  .appName("SparkApp")
  .config("spark.some.config.option", "some-value")
  .getOrCreate()
val rdd = sc.textFile(args(0))
val schemaString = args(1)
val pattern = new Regex(args(2))

val fields = schemaString.split(" ")
  .map(fieldName => StructField(fieldName, StringType, nullable = true))
val schema = StructType(fields)

val matches = rdd.map { x => pattern.findFirstMatchIn(x) }.map{ x => x.map{x => x.subgroups}}
val values = matches.map { x => x.map { x => Row(x.toArray) }}

在值我得到RDD[Option[Row]] 任何建議。

您正在獲取RDD[Option[Row]]因為您進行了正則表達式。以下是findFirstMatchIn的定義,它返回Option

def findFirstMatchIn(source: CharSequence): Option[Match] 

為了避免這種情況

val matches = rdd.map { x => pattern.findFirstMatchIn(x) }.map { x => x.map { x => x.subgroups }.get }
val values = matches.map { x => x.map { x => Row(x.toArray) } }

結果

RDD[List[Row]]

為防御getOrElse ,您可以考慮使用getOrElse而不是get

如果只需要RDD[Row]也可以考慮flatmap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM