Spark - 将CSV文件加载为DataFrame?

时间:2015-04-17 16:10:21

标签: scala apache-spark hadoop apache-spark-sql hdfs

我想在spark中读取CSV并将其转换为DataFrame并将其存储在带有df.registerTempTable("table_name")的HDFS中

我试过了:

scala> val df = sqlContext.load("hdfs:///csv/file/dir/file.csv")

我得到的错误:

java.lang.RuntimeException: hdfs:///csv/file/dir/file.csv is not a Parquet file. expected magic number at tail [80, 65, 82, 49] but found [49, 59, 54, 10]
    at parquet.hadoop.ParquetFileReader.readFooter(ParquetFileReader.java:418)
    at org.apache.spark.sql.parquet.ParquetRelation2$MetadataCache$$anonfun$refresh$6.apply(newParquet.scala:277)
    at org.apache.spark.sql.parquet.ParquetRelation2$MetadataCache$$anonfun$refresh$6.apply(newParquet.scala:276)
    at scala.collection.parallel.mutable.ParArray$Map.leaf(ParArray.scala:658)
    at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply$mcV$sp(Tasks.scala:54)
    at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:53)
    at scala.collection.parallel.Task$$anonfun$tryLeaf$1.apply(Tasks.scala:53)
    at scala.collection.parallel.Task$class.tryLeaf(Tasks.scala:56)
    at scala.collection.parallel.mutable.ParArray$Map.tryLeaf(ParArray.scala:650)
    at scala.collection.parallel.AdaptiveWorkStealingTasks$WrappedTask$class.compute(Tasks.scala:165)
    at scala.collection.parallel.AdaptiveWorkStealingForkJoinTasks$WrappedTask.compute(Tasks.scala:514)
    at scala.concurrent.forkjoin.RecursiveAction.exec(RecursiveAction.java:160)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

在Apache Spark中将CSV文件作为DataFrame加载的正确命令是什么?

15 个答案:

答案 0 :(得分:141)

解析CSV并使用Spark 2.x

加载为DataFrame / DataSet

首先初始化SparkSession对象默认情况下,它在shell中可用spark

val spark = org.apache.spark.sql.SparkSession.builder
        .master("local")
        .appName("Spark CSV Reader")
        .getOrCreate;
  

使用以下任意一种方式将CSV加载为DataFrame/DataSet

1。以程序化方式执行

 val df = spark.read
         .format("csv")
         .option("header", "true") //first line in file has headers
         .option("mode", "DROPMALFORMED")
         .load("hdfs:///csv/file/dir/file.csv")

2。 You can do this SQL way as well

 val df = spark.sql("SELECT * FROM csv.`hdfs:///csv/file/dir/file.csv`")

<强>依赖关系

 "org.apache.spark" % "spark-core_2.11" % 2.0.0,
 "org.apache.spark" % "spark-sql_2.11" % 2.0.0,

Spark版本&lt; 2.0

val df = sqlContext.read
    .format("com.databricks.spark.csv")
    .option("header", "true") 
    .option("mode", "DROPMALFORMED")
    .load("csv/file/path"); 

<强>依赖关系:

"org.apache.spark" % "spark-sql_2.10" % 1.6.0,
"com.databricks" % "spark-csv_2.10" % 1.6.0,
"com.univocity" % "univocity-parsers" % LATEST,

答案 1 :(得分:123)

spark-csv是Spark核心功能的一部分,并不需要单独的库。 所以你可以这么做,例如

df = spark.read.format("csv").option("header", "true").load("csvfile.csv")

在scala中,(这适用于任何格式分隔符提及&#34;,&#34;对于csv,&#34; \ t&#34;对于tsv等) val df = sqlContext.read.format("com.databricks.spark.csv") .option("delimiter", ",") .load("csvfile.csv")

答案 2 :(得分:13)

Hadoop为2.6,Spark为1.6且没有“databricks”软件包。

import org.apache.spark.sql.types.{StructType,StructField,StringType,IntegerType};
import org.apache.spark.sql.Row;

val csv = sc.textFile("/path/to/file.csv")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0),row(1).toInt))

val schema = new StructType()
    .add(StructField("id", StringType, true))
    .add(StructField("val", IntegerType, true))

val df = sqlContext.createDataFrame(rdd, schema)

答案 3 :(得分:11)

使用Spark 2.0,您可以通过以下方式阅读CSV

val conf = new SparkConf().setMaster("local[2]").setAppName("my app")
val sc = new SparkContext(conf)
val sparkSession = SparkSession.builder
  .config(conf = conf)
  .appName("spark session example")
  .getOrCreate()

val path = "/Users/xxx/Downloads/usermsg.csv"
val base_df = sparkSession.read.option("header","true").
  csv(path)

答案 4 :(得分:8)

在Java 1.8中这段代码片段非常适合读取CSV文件

POM.xml

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.10</artifactId>
    <version>2.0.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.scala-lang/scala-library -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.8</version>
</dependency>
<dependency>
    <groupId>com.databricks</groupId>
    <artifactId>spark-csv_2.10</artifactId>
    <version>1.4.0</version>
</dependency>

Java

SparkConf conf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
// create Spark Context
SparkContext context = new SparkContext(conf);
// create spark Session
SparkSession sparkSession = new SparkSession(context);

Dataset<Row> df = sparkSession.read().format("com.databricks.spark.csv").option("header", true).option("inferSchema", true).load("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");

        //("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");
System.out.println("========== Print Schema ============");
df.printSchema();
System.out.println("========== Print Data ==============");
df.show();
System.out.println("========== Print title ==============");
df.select("title").show();

答案 5 :(得分:4)

Penny的Spark 2示例是在spark2中执行此操作的方法。还有一个技巧:通过将选项inferSchema设置为true

,通过对数据进行初始扫描为您生成标题

然后,假设spark是您设置的一个火花会话,是加载到S3上的亚马逊主机的所有Landsat图像的CSV索引文件中的操作。

  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */

val csvdata = spark.read.options(Map(
    "header" -> "true",
    "ignoreLeadingWhiteSpace" -> "true",
    "ignoreTrailingWhiteSpace" -> "true",
    "timestampFormat" -> "yyyy-MM-dd HH:mm:ss.SSSZZZ",
    "inferSchema" -> "true",
    "mode" -> "FAILFAST"))
  .csv("s3a://landsat-pds/scene_list.gz")

坏消息是:这会触发扫描文件;对于像这个20 + MB压缩CSV文件那样大的东西,在长途连接上可能需要30秒。请记住:一旦你进入架构,你最好手动编写架构编码。

(代码片段Apache软件许可证2.0获得许可以避免出现歧义;我作为S3集成的演示/集成测试已完成的事情)

答案 6 :(得分:3)

解析CSV文件有很多挑战,如果文件大小较大,并且列值中包含非英语/转义符/分隔符/其他字符,它会不断累加,这可能会导致解析错误。

那么魔术就在所使用的选项中。下面的代码为我工作并希望可以覆盖大多数的情况:

### Create a Spark Session
spark = SparkSession.builder.master("local").appName("Classify Urls").getOrCreate()

### Note the options that are used. You may have to tweak these in case of error
html_df = spark.read.csv(html_csv_file_path, 
                         header=True, 
                         multiLine=True, 
                         ignoreLeadingWhiteSpace=True, 
                         ignoreTrailingWhiteSpace=True, 
                         encoding="UTF-8",
                         sep=',',
                         quote='"', 
                         escape='"',
                         maxColumns=2,
                         inferSchema=True)

希望有帮助。有关更多信息,请参见:Using PySpark 2 to read CSV having HTML source code

注意:上面的代码来自Spark 2 API,其中CSV文件读取API与Spark可安装的内置软件包捆绑在一起。

注意:PySpark是Spark的Python包装器,并且与Scala / Java共享相同的API。

答案 7 :(得分:1)

如果要使用Scala 2.11和Apache 2.0或更高版本来构建jar。

无需创建sqlContextsparkContext对象。只需一个SparkSession对象就可以满足所有需求。

以下是可以正常工作的mycode:

import org.apache.spark.sql.{DataFrame, Row, SQLContext, SparkSession}
import org.apache.log4j.{Level, LogManager, Logger}

object driver {

  def main(args: Array[String]) {

    val log = LogManager.getRootLogger

    log.info("**********JAR EXECUTION STARTED**********")

    val spark = SparkSession.builder().master("local").appName("ValidationFrameWork").getOrCreate()
    val df = spark.read.format("csv")
      .option("header", "true")
      .option("delimiter","|")
      .option("inferSchema","true")
      .load("d:/small_projects/spark/test.pos")
    df.show()
  }
}

如果您在集群中运行,只需在定义.master("local")对象的同时将.master("yarn")更改为sparkBuilder

Spark文档涵盖了以下内容: https://spark.apache.org/docs/2.2.0/sql-programming-guide.html

答案 8 :(得分:1)

将以下Spark依赖项添加到POM文件:

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.2.0</version>
</dependency>

//火花配置:

val spark = SparkSession.builder()。master(“ local”)。appName(“ Sample App”)。getOrCreate()

//读取csv文件:

val df = spark.read.option(“ header”,“ true”)。csv(“ FILE_PATH”)

//显示输出

df.show()

答案 9 :(得分:1)

在Spark 2.4+中,如果要从本地目录加载csv,则可以使用2个会话并将其加载到hive中。第一个会话应使用master()config创建为“ local [*]”,第二个会话应启用“ yarn”和Hive。

下面的一个对我有用。

import org.apache.log4j.{Level, Logger}
import org.apache.spark._
import org.apache.spark.rdd._
import org.apache.spark.sql._

object testCSV { 

  def main(args: Array[String]) {
    Logger.getLogger("org").setLevel(Level.ERROR)
    val spark_local = SparkSession.builder().appName("CSV local files reader").master("local[*]").getOrCreate()

    import spark_local.implicits._
    spark_local.sql("SET").show(100,false)
    val local_path="/tmp/data/spend_diversity.csv"  // Local file
    val df_local = spark_local.read.format("csv").option("inferSchema","true").load("file://"+local_path) // "file://" is mandatory
    df_local.show(false)

    val spark = SparkSession.builder().appName("CSV HDFS").config("spark.sql.warehouse.dir", "/apps/hive/warehouse").enableHiveSupport().getOrCreate()

    import spark.implicits._
    spark.sql("SET").show(100,false)
    val df = df_local
    df.createOrReplaceTempView("lcsv")
    spark.sql(" drop table if exists work.local_csv ")
    spark.sql(" create table work.local_csv as select * from lcsv ")

   }

spark2-submit --master "yarn" --conf spark.ui.enabled=false testCSV.jar一起运行时,它运行良好,并在配置单元中创建了表。

答案 10 :(得分:0)

默认文件格式为Parquet,带有spark.read ..,文件读取csv,这就是为什么您遇到异常的原因。用您要使用的api指定csv格式

答案 11 :(得分:0)

加载CSV文件并将结果作为DataFrame返回。

df=sparksession.read.option("header", true).csv("file_name.csv")

Dataframe将文件视为csv格式。

答案 12 :(得分:0)

如果使用spark 2.0+,请尝试此操作

For non-hdfs file:
df = spark.read.csv("file:///csvfile.csv")


For hdfs file:
df = spark.read.csv("hdfs:///csvfile.csv")

For hdfs file (with different delimiter than comma:
df = spark.read.option("delimiter","|")csv("hdfs:///csvfile.csv")

注意:-此功能适用于任何定界文件。只需使用option(“ delimiter”,)即可更改值。

希望这会有所帮助。

答案 13 :(得分:-1)

借助内置的Spark csv,您可以使用适用于Spark> 2.0的新SparkSession对象轻松完成此操作。

val df = spark.
        read.
        option("inferSchema", "false").
        option("header","true").
        option("mode","DROPMALFORMED").
        option("delimiter", ";").
        schema(dataSchema).
        csv("/csv/file/dir/file.csv")
df.show()
df.printSchema()

您可以设置各种选项。

  • header:文件是否在顶部包含标题行
  • inferSchema:是否要自动推断模式。默认值为true。我总是喜欢提供架构以确保正确的数据类型。
  • mode:解析模式,PERMISSIVE,DROPMALFORMED或FAILFAST
  • delimiter:要指定定界符,默认为逗号(',')

答案 14 :(得分:-1)

从系统上的相对路径读取。此解决方案使用System.getProperty方法获取当前目录,并进一步使用相对路径加载文件。

scala> val path = System.getProperty("user.dir").concat("/../2015-summary.csv")
scala> val csvDf = spark.read.option("inferSchema","true").option("header", "true").csv(path)
scala> csvDf.take(3)

spark:2.4.4 scala:2.11.12