簡體   English   中英

如何使用DataFrame API和SCALA在Spark中讀取固定長度的文件

[英]How to read a fixed length file in Spark using DataFrame API and SCALA

我有一個固定長度的文件(示例如下所示),我想使用SCALA(不是python或java)在Spark中使用DataFrames API讀取此文件。 使用DataFrames API,可以使用多種方法讀取textFile,json文件等,但不確定是否可以讀取固定長度的文件。 我正在互聯網上搜索此文件,並找到了github 鏈接 ,但出於此目的,我必須下載spark-fixedwidth-assembly-1.0.jar ,但是無法在任何地方找到該jar。 我在這里完全迷失了,需要您的建議和幫助。 Stackoverflow中有幾篇文章,但與Scala和DataFrame API沒有關系。

這是文件

56 apple     TRUE 0.56
45 pear      FALSE1.34
34 raspberry TRUE 2.43
34 plum      TRUE 1.31
53 cherry    TRUE 1.4 
23 orange    FALSE2.34
56 persimmon FALSE23.2

每列的固定寬度為3、10、5、4

請提出您的意見。

好吧...使用子字符串來換行。 然后修整以去除wheitespaces。 然后做任何你想做的。

case class DataUnit(s1: Int, s2: String, s3:Boolean, s4:Double)

sc.textFile('your_file_path')
  .map(l => (l.substring(0, 3).trim(), l.substring(3, 13).trim(), l.substring(13,18).trim(), l.substring(18,22).trim()))
  .map({ case (e1, e2, e3, e4) => DataUnit(e1.toInt, e2, e3.toBoolean, e4.toDouble) })
  .toDF

固定長度格式很舊,我找不到適合這種格式的Scala庫...因此我創建了自己的庫。

您可以在這里查看: https : //github.com/atais/Fixed-Length

與星火用法很簡單,你會得到一個DataSet的對象!

首先,您需要創建對象的描述,例如:

case class Employee(name: String, number: Option[Int], manager: Boolean)

object Employee {

    import com.github.atais.util.Read._
    import cats.implicits._
    import com.github.atais.util.Write._
    import Codec._

    implicit val employeeCodec: Codec[Employee] = {
      fixed[String](0, 10) <<:
        fixed[Option[Int]](10, 13, Alignment.Right) <<:
        fixed[Boolean](13, 18)
    }.as[Employee]
}

然后再使用解析器:

val input = sql.sparkContext.textFile(file)
               .filter(_.trim.nonEmpty)
               .map(Parser.decode[Employee])
               .flatMap {
                  case Right(x) => Some(x)
                  case Left(e) =>
                         System.err.println(s"Failed to process file $file, error: $e")
                         None
               }
sql.createDataset(input)

暫無
暫無

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

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