Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spark-Scala to download a CSV file from the web?

world,

How to use Spark-Scala to download a CSV file from the web and load the file into a spark-csv DataFrame?

Currently I depend on curl in a shell command to get my CSV file.

Here is the syntax I want to enhance:

/* fb_csv.scala
This script should load FB prices from Yahoo.

Demo:
spark-shell -i fb_csv.scala
*/

// I should get prices:
import sys.process._
"/usr/bin/curl -o /tmp/fb.csv http://ichart.finance.yahoo.com/table.csv?s=FB"!

import org.apache.spark.sql.SQLContext

val sqlContext = new SQLContext(sc)

val fb_df = sqlContext.read.format("com.databricks.spark.csv").option("header","true").option("inferSchema","true").load("/tmp/fb.csv")

fb_df.head(9)

I want to enhance the above script so it is pure Scala with no shell syntax inside.

like image 392
user3676943 Avatar asked Sep 25 '16 08:09

user3676943


2 Answers

val content = scala.io.Source.fromURL("http://ichart.finance.yahoo.com/table.csv?s=FB").mkString

val list = content.split("\n").filter(_ != "")

val rdd = sc.parallelize(list)

val df = rdd.toDF
like image 145
Samar Avatar answered Nov 15 '22 04:11

Samar


Found better answer from Process CSV from REST API into Spark

Here you go:

import scala.io.Source._
import org.apache.spark.sql.{Dataset, SparkSession}

var res = fromURL(url).mkString.stripMargin.lines.toList
val csvData: Dataset[String] = spark.sparkContext.parallelize(res).toDS()

val frame = spark.read.option("header", true).option("inferSchema",true).csv(csvData)
frame.printSchema()
like image 25
jack Avatar answered Nov 15 '22 03:11

jack