3
votes

I have CSV data:

"id","price"
"1","79.07"
"2","91.27"
"3","85.6"

Reading it using SparkSession:

def readToDs(resource: String, schema: StructType): Dataset = {
    sparkSession.read
      .option("header", "true")
      .schema(schema)
      .csv(resource)
      .as[ItemPrice]
}

Case class:

case class ItemPrice(id: Long, price: BigDecimal)

Printing Dataset:

def main(args: Array[String]): Unit = {
    val prices: Dataset = 
        readToDs("src/main/resources/app/data.csv", Encoders.product[ItemPrice].schema);
    prices.show();
}

Output:

+----------+--------------------+
|        id|               price|
+----------+--------------------+
|         1|79.07000000000000...|
|         2|91.27000000000000...|
|         3|85.60000000000000...|
+----------+--------------------+

Desired output:

+----------+--------+
|        id|   price|
+----------+--------+
|         1|   79.07|
|         2|   91.27|
|         3|   85.6 |
+----------+--------+

The option I already know:

Define schema manually with hardcoded column order and datatypes like:

def defineSchema(): StructType =
    StructType(
      Seq(StructField("id", LongType, nullable = false)) :+
        StructField("price", DecimalType(3, 2), nullable = false)
    )

And use it like:

val prices: Dataset = readToDs("src/main/resources/app/data.csv", defineSchema);

How can I set precision (3,2) without manually defining all structure?

3
could you pls check the UPDATE1 in answerstack0114106

3 Answers

2
votes

Assuming you get your csv as

scala> val df = Seq(("1","79.07","89.04"),("2","91.27","1.02"),("3","85.6","10.01")).toDF("item","price1","price2")
df: org.apache.spark.sql.DataFrame = [item: string, price1: string ... 1 more field]

scala> df.printSchema
root
 |-- item: string (nullable = true)
 |-- price1: string (nullable = true)
 |-- price2: string (nullable = true)

You can cast it like below

scala> val df2 = df.withColumn("price1",'price1.cast(DecimalType(4,2)))
df2: org.apache.spark.sql.DataFrame = [item: string, price1: decimal(4,2) ... 1 more field]

scala> df2.printSchema
root
 |-- item: string (nullable = true)
 |-- price1: decimal(4,2) (nullable = true)
 |-- price2: string (nullable = true)


scala>

Now, if you know the list of decimal columns from the csv.. with an array, you can do it dynamically like below

scala> import org.apache.spark.sql.types._
import org.apache.spark.sql.types._

scala> val decimal_cols = Array("price1","price2")
decimal_cols: Array[String] = Array(price1, price2)

scala> val df3 = decimal_cols.foldLeft(df){ (acc,r) => acc.withColumn(r,col(r).cast(DecimalType(4,2))) }
df3: org.apache.spark.sql.DataFrame = [item: string, price1: decimal(4,2) ... 1 more field]

scala> df3.show
+----+------+------+
|item|price1|price2|
+----+------+------+
|   1| 79.07| 89.04|
|   2| 91.27|  1.02|
|   3| 85.60| 10.01|
+----+------+------+


scala> df3.printSchema
root
 |-- item: string (nullable = true)
 |-- price1: decimal(4,2) (nullable = true)
 |-- price2: decimal(4,2) (nullable = true)


scala>

Does that help?.

UPDATE1:

Reading the csv file using inferSchema and then casting all the double fields to DecimalType(4,2) dynamically.

val df = spark.read.format("csv").option("header","true").option("inferSchema","true").load("in/items.csv")
df.show
df.printSchema()
val decimal_cols = df.schema.filter( x=> x.dataType.toString == "DoubleType" ).map(x=>x.name)
// or df.schema.filter( x=> x.dataType==DoubleType )
val df3 = decimal_cols.foldLeft(df){ (acc,r) => acc.withColumn(r,col(r).cast(DecimalType(4,2))) }
df3.printSchema()
df3.show()

Results:

+-----+------+------+
|items|price1|price2|
+-----+------+------+
|    1| 79.07| 89.04|
|    2| 91.27|  1.02|
|    3|  85.6| 10.01|
+-----+------+------+

root
 |-- items: integer (nullable = true)
 |-- price1: double (nullable = true)
 |-- price2: double (nullable = true)

root
 |-- items: integer (nullable = true)
 |-- price1: decimal(4,2) (nullable = true)
 |-- price2: decimal(4,2) (nullable = true)

+-----+------+------+
|items|price1|price2|
+-----+------+------+
|    1| 79.07| 89.04|
|    2| 91.27|  1.02|
|    3| 85.60| 10.01|
+-----+------+------+
0
votes

An option is to define a converter for input schema:

def defineDecimalType(schema: StructType): StructType = {
    new StructType(
      schema.map {
        case StructField(name, dataType, nullable, metadata) =>
          if (dataType.isInstanceOf[DecimalType])
            // Pay attention to max precision in the source data
            StructField(name, new DecimalType(20, 2), nullable, metadata)
          else 
            StructField(name, dataType, nullable, metadata)
      }.toArray
    )
} 

def main(args: Array[String]): Unit = {
    val prices: Dataset = 
        readToDs("src/main/resources/app/data.csv", defineDecimalType(Encoders.product[ItemPrice].schema));
    prices.show();
}

The drawback of this approach is that this mapping applied to every column, and if you have an ID that does not fits in exact precision (let's say ID = 10000 to DecimalType(3, 2)) you'll get an exception:

Caused by: java.lang.IllegalArgumentException: requirement failed: Decimal precision 4 exceeds max precision 3 at scala.Predef$.require(Predef.scala:224) at org.apache.spark.sql.types.Decimal.set(Decimal.scala:113) at org.apache.spark.sql.types.Decimal$.apply(Decimal.scala:426) at org.apache.spark.sql.execution.datasources.csv.CSVTypeCast$.castTo(CSVInferSchema.scala:273) at org.apache.spark.sql.execution.datasources.csv.CSVRelation$$anonfun$csvParser$3.apply(CSVRelation.scala:125) at org.apache.spark.sql.execution.datasources.csv.CSVRelation$$anonfun$csvParser$3.apply(CSVRelation.scala:94) at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$buildReader$1$$anonfun$apply$2.apply(CSVFileFormat.scala:167) at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anonfun$buildReader$1$$anonfun$apply$2.apply(CSVFileFormat.scala:166)

So that's why it's important to keep precision higher than biggest decimal in the source data:

if (dataType.isInstanceOf[DecimalType])
    StructField(name, new DecimalType(20, 2), nullable, metadata)
-1
votes

I tried loading the sample data using 2 different CSV files and it is working fine and results are as expected for the following code. I am using Spark 2.3.1 on windows.

//read with double quotes
val df1 = spark.read
.format("csv")
.option("header","true")
.option("inferSchema","true")
.option("nullValue","")
.option("mode","failfast")
.option("path","D:/bitbuket/spark-examples/53667822/string.csv")
.load()

df1.show
/*
scala> df1.show
+---+-----+
| id|price|
+---+-----+
|  1|79.07|
|  2|91.27|
|  3| 85.6|
+---+-----+
*/

//read with without quotes
val df2 = spark.read
.format("csv")
.option("header","true")
.option("inferSchema","true")
.option("nullValue","")
.option("mode","failfast")
.option("path","D:/bitbuket/spark-examples/53667822/int-double.csv")
.load()

df2.show

/*
scala> df2.show
+---+-----+
| id|price|
+---+-----+
|  1|79.07|
|  2|91.27|
|  3| 85.6|
+---+-----+
*/

Result with your data set