如何从spark scala中的外部文件读取文件路径和模式?

zf9nrax1  于 2021-07-13  发布在  Spark
关注(0)|答案(1)|浏览(308)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

两个月前关门了。
改进这个问题
我是scala和spark的新手,想知道如何使用intellij idea停止scala中的硬编码。
我的模式是

val schema="actor_id int,first_name string,last_name string,last_update timestamp"

path = E:\Salman\Hive-Data\actor.csv
p8h8hvxi

p8h8hvxi1#

如果不想硬编码,可以使用文件存储配置。
然后,您可以使用java属性类或类型安全配置库或scala.io库来检索代码中的这些信息。
假设您想使用sparkapi读取一些文件,而不想硬编码文件路径。
首先,创建一个文件并保存信息,如下所示:

file1Path=/path/to/file1
file2Path=/path/to/file2
file3Path=/path/to/file3

代码:

// Fetch configurations using Properties class
import java.util.Properties
import java.io._

val p=new Properties()
// pass configuration file name
p.load(new FileReader("configs.properties"))
val file1Path=p.getProperty("file1Path")
val file2Path=p.getProperty("file2Path")

// now use spark API
val spark = SparkSession.builder().master("local[*]").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
import spark.implicits._
import org.apache.spark.sql.types._

val df1 = spark.read.csv(file1Path)
val df2 = spark.read.csv(file2Path)

读取csv时不需要显式指定模式。如果我们使用如下代码所示的选项,spark.read.csv会处理这个问题,

val df = spark.read.option("inferSchema",true).option("header",true).csv(file1Path)

如果您想显式地指定模式而不进行硬编码,那么再次使用以前的配置文件。
向文件中添加以下内容。

file1Schema=actor_id int,first_name string,last_name string,last_update timestamp

代码:

//Fetch schema using previous property object
 val schemaString=p.getProperty("file1Schema")

// map for changing passed type to spark data type
val typeToSparkType = Map("int" -> IntegerType, "string" -> StringType,"date"->DateType,"timestamp"->TimestampType)

val colNameType = schemaString.split(",").map{s=>
    val values=s.split("\\s+")
    // Tuple of column name and type
    (values(0),values(1))
}

// prepare schema
var schema = StructType(colNameType.map(t => StructField(t._1, typeToSparkType(t._2), true)))

// read csv with custom schema
spark.read.schema(schema).csv(filePath1)

您可以使用我在开始阅读配置文件时提到的其他可选库。

相关问题