Creating Datasets
Datasets are similar to RDDs, however, instead of using Java serialization or Kryo they use a specialized Encoder to serialize the objects for processing or transmitting over the network.
While both encoders and standard serialization are responsible for turning an object into bytes, encoders are code generated dynamically and use a format that allows Spark to perform many operations like filtering, sorting and hashing without deserializing the bytes back into an object.
1
import spark.implicits._
2
case class Person(name: String, age: Long)
3
​
4
// Encoders are created for case classes
5
val caseClassDS = Seq(Person("Andy", 32)).toDS()
6
caseClassDS.show()
7
// +----+---+
8
// |name|age|
9
// +----+---+
10
// |Andy| 32|
11
// +----+---+
12
​
13
// Encoders for most common types are automatically provided by importing spark.implicits._
14
val primitiveDS = Seq(1, 2, 3).toDS()
15
primitiveDS.map(_ + 1).collect() // Returns: Array(2, 3, 4)
16
​
17
// DataFrames can be converted to a Dataset by providing a class. Mapping will be done by name
18
val path = "file:///home/dv6/spark/spark/examples/src/main/resources/people.json"
19
val peopleDS = spark.read.json(path).as[Person]
20
peopleDS.getClass
Copied!
Last modified 1yr ago
Copy link