【问题标题】:Escape quotes is not working in spark 2.2.0 while reading csv阅读 csv 时,转义引号在 spark 2.2.0 中不起作用
【发布时间】:2018-10-25 18:28:32
【问题描述】:

我正在尝试读取以制表符分隔但无法读取所有记录的分隔文件。

这是我的输入记录:

head1   head2   head3
a   b   c
a2  a3  a4
a1  "b1 "c1

我的代码:

var inputDf = sparkSession.read
                  .option("delimiter","\t")
                  .option("header", "true")
//                  .option("inferSchema", "true")
                  .option("nullValue", "")
                  .option("escape","\"")
                  .option("multiLine", true)
                  .option("nullValue", null)
                  .option("nullValue", "NULL")
                  .schema(finalSchema)
                  .csv("file:///C:/Users/prhasija/Desktop/retriedAddresses_4.txt")
//                  .csv(inputPath)
                  .na.fill("")
//                  .repartition(4)

                  println(inputDf.count)

输出:

2 records

为什么它没有返回 3 作为计数?

【问题讨论】:

  • 最后一行格式错误。
  • 解决方法是什么。我必须用引号阅读这些数据
  • 你的 finalSchema 是什么样的?
  • 它是 structType(Queue[StructField]())。我保存为字符串的所有列

标签: scala apache-spark mapreduce apache-spark-sql spark-streaming


【解决方案1】:

我认为您需要在阅读中添加以下选项:.option("escape", "\\") 和 .option("quote", "\\")

val test = spark.read
    .option("header", true)
    .option("quote", "\\")
    .option("escape", "\\")
    .option("delimiter", ",")
    .csv(".../test.csv")

这是我使用的测试 csv:

a,b,c
1,b,a
5,d,e
5,"a,"f

完整输出:

scala> val test = spark.read.option("header", true).option("quote", "\\").option("escape", "\\").option("delimiter", ",").csv("./test.csv")
test: org.apache.spark.sql.DataFrame = [a: string, b: string ... 1 more field]

scala> test.show
+---+---+---+
|  a|  b|  c|
+---+---+---+
|  1|  b|  a|
|  5|  d|  e|
|  5| "a| "f|
+---+---+---+


scala> test.count
res11: Long = 3

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 2018-05-25
    • 2016-09-10
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2018-07-25
    相关资源
    最近更新 更多