Reference: http://spark.apache.org/docs/latest/sql-programming-guide.html
1) Use Maven to build a Scala project.
1.1) Add the Pom dependency package file as follows:
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.10</artifactId>
<version>2.2.2</version>
<!--<scope>runtime</scope>-->
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>2.2.2</version>
</dependency>
1.2) New Scala class, code and functions described below:
Package Com.fishjar.sparksql
Import Org.apache.spark.sql._
Import Org.apache.spark.sql.expressions. {aggregator, Mutableaggregationbuffer, userdefinedaggregatefunction}
Import Org.apache.spark.sql.types._
/**
* Created by Fishjar on 2018/8/22.
*/
Object Sparksqldemo {
The definition of case class is to refer to the outside of the case class function. Because I have only one main function, so I moved the case class outside.
Case class Person (name:string, Age:long)
def main (args:array[string]): Unit = {
Val path1= "D:\\test\\people.json"
Val path2= "D:\\test\\people.txt"
1) Create Sparksession
System.setproperty ("Hadoop.home.dir", "f:\\hadp-dev\\hadoop-2.7.1");
Val Spark = Sparksession
. Builder ()
. AppName ("Spark SQL Basic Example")
. Master ("local[2]")
. config ("spark.some.config.option", "Some-value")
. Getorcreate ()
For implicit conversions like converting RDDs to Dataframes
Import Spark.implicits._
2) Create Dataframe
Val df = Spark.read.json (path1)
2.1) Display the contents of Dataframe
Df.show ()
2.2) schema in the Print tree format
Df.printschema ()
2.3) Select the Name column
Df.select ("name"). Show ()
2.4) Select all data and add the Age column 1
Df.select ($ "name", $ "age" + 1). Show ()
2.5) filter for data older than 21
Df.filter ($ "age" >). Show ()
2.6) Classify statistics according to age
Df.groupby ("Age"). Count (). Show ()
3) Create the Dataframe in an attempted manner and return the result set
3.1) Register Dataframe as a view
Df.createorreplacetempview ("People")
3.2) Query view
Val sqldf = Spark.sql ("Select * from people")
println ("*******createorreplacetempview*******")
Sqldf.show ()
3.3) Register Dataframe as a global view
Df.createglobaltempview ("People")
println ("*******createglobaltempview*****")
Spark.sql ("SELECT * from Global_temp.people"). Show ()
Spark.newsession (). SQL ("SELECT * from Global_temp.people"). Show ()
4 Creating datasets
println ("*******4 Create DataSet * * * * * * * *")
Encoders is created for case classes
Val Caseclassds = Seq (Person ("Andy", +)). ToDS ()
Caseclassds.show ()
Encoders for most common types is automatically provided by importing Spark.implicits._
Val primitiveds = Seq (1, 2, 3). ToDS ()
Primitiveds.map (_ + 1). Collect ()//Returns:array (2, 3, 4)
For (Arg <-primitiveds) println (ARG)
Dataframes can converted to a Dataset by providing a class. Mapping would be do by name
Val peopleds = Spark.read.json (path1). As[person]
println ("********peopleds*******")
Peopleds.show ()
5 Use the schema indirectly using reflection
Inferring the Schema Using Reflection
println ("5 uses reflection to indirectly use schema")
For implicit conversions from RDDs to Dataframes
Import Spark.implicits._
Create an RDD of person objects from a text file, convert it to a Dataframe
Val Peopledf = Spark.sparkcontext
. Textfile ("D:\\test\\aaa.txt")
. Map (_.split (","))
. map (attributes = person (attributes (1), attributes (0). Trim.toint))
. TODF ()
Register the DataFrame as a temporary view
Peopledf.createorreplacetempview ("People")
SQL statements can be run by using the SQL methods provided by Spark
Val teenagersdf = Spark.sql ("Select name, age from people WHERE age between and 19")
Teenagersdf.show (1)
The columns of a row in the result can be accessed by field index
Teenagersdf.map (teenager = "Name:" + teenager (0)). Show ()
or by field name
Teenagersdf.map (teenager = "Name:" + teenager.getas[string] ("name"). Show ()
No pre-defined encoders for Dataset[map[k,v]], define explicitly
Implicit val mapencoder = org.apache.spark.sql.encoders.kryo[map[string, any]]
Primitive types and Case classes can be also defined as
Implicit Val stringintmapencoder:encoder[map[string, any]] = Expressionencoder ()
ROW.GETVALUESMAP[T] Retrieves multiple columns at once into a map[string, T]
println ("Encoders")
Teenagersdf.map (teenager = Teenager.getvaluesmap[any] (List ("name", "Age")). Collect ()
6 programmatically specifying the Schema
println ("**********programmatically specifying the Schema")
Import Org.apache.spark.sql.types._
Create an RDD
Val Peoplerdd = Spark.sparkContext.textFile ("D:\\test\\people.txt")
The schema is encoded in a string
Val schemastring = "Name Age"
Generate the schema based on the string of the schema
Val fields = Schemastring.split ("")
. map (FieldName = Structfield (FieldName, stringtype, nullable = True))
Val schema = Structtype (Fields)
Convert Records of the RDD (people) to Rows
Val Rowrdd = Peoplerdd
. Map (_.split (","))
. map (attributes = Row (attributes (0), attributes (1). Trim))
Apply the schema to the RDD
Val peopleDF2 = Spark.createdataframe (Rowrdd, schema)
Creates a temporary view using the DataFrame
Peopledf2.createorreplacetempview ("People")
SQL can is run over a temporary view created using Dataframes
Val results = spark.sql ("Select name from people")
Results.map (attributes = "Name:" + attributes (0)). Show ()
Results.show ()
Peopledf2.show ()
7 user-defined functions
println ("*********7 User Custom Function ************")
Untyped user-defined Aggregate Functions
Register the function to access it
Spark.udf.register ("Myaverage", Myaverage)
Val df2 = Spark.read.json ("D:\\test\\employees.json")
Df2.createorreplacetempview ("Employees")
Df2.show ()
Val result = Spark.sql ("Select Myaverage (Salary) as average_salary from Employees")
Result.show ()
8 user-defined type-safe functions
Type-safe user-defined Aggregate Functions
println ("********** user-defined type-safe function **********")
Val ds = Spark.read.json ("D:\\test\\employees.json"). As[employee]
Ds.show ()
Convert the function to a ' typedcolumn ' and give it a name
Val averagesalary = MyAverage2.toColumn.name ("Average_salary")
Val result2 = Ds.select (averagesalary)
Result2.show ()
}
Object Myaverage extends Userdefinedaggregatefunction {
Data types of input arguments of this aggregate function
def inputschema:structtype = Structtype (Structfield ("Inputcolumn", Longtype):: Nil)
Data types of values in the aggregation buffer
def bufferschema:structtype = {
Structtype (Structfield ("sum", Longtype):: Structfield ("Count", Longtype):: Nil)
}
The data type of the returned value
def datatype:datatype = Doubletype
Whether This function, returns the same output on the identical input
def Deterministic:boolean = True
Initializes the given aggregation buffer. The buffer itself is a ' Row ', addition to
Standard methods type retrieving a value at an index (e.g., get (), Getboolean ()), provides
The opportunity to update its values. Note that arrays and maps inside the buffer is still
Immutable.
def initialize (buffer:mutableaggregationbuffer): Unit = {
Buffer (0) = 0L
Buffer (1) = 0L
}
Updates the given aggregation buffer ' buffer ' with new input data from ' input '
def update (Buffer:mutableaggregationbuffer, input:row): Unit = {
if (!input.isnullat (0)) {
Buffer (0) = Buffer.getlong (0) + input.getlong (0)
Buffer (1) = Buffer.getlong (1) + 1
}
}
Merges aggregation buffers and stores the updated buffer values back to ' buffer1 '
def merge (Buffer1:mutableaggregationbuffer, buffer2:row): Unit = {
Buffer1 (0) = Buffer1.getlong (0) + buffer2.getlong (0)
Buffer1 (1) = Buffer1.getlong (1) + Buffer2.getlong (1)
}
Calculates the final result
def evaluate (buffer:row): Double = Buffer.getlong (0). Todouble/buffer.getlong (1)
}
Case Class Employee (name:string, Salary:long)
Case Class Average (Var Sum:long, var count:long)
Object MyAverage2 extends Aggregator[employee, Average, Double] {
A zero value for this aggregation. Should satisfy the property, any B + zero = b
def zero:average = Average (0L, 0L)
Combine the values to produce a new value. For performance, the function may modify ' buffer '
and return it instead of constructing a new object
def reduce (buffer:average, employee:employee): Average = {
Buffer.sum + = Employee.salary
Buffer.count + = 1
Buffer
}
Merge Intermediate values
def merge (B1:average, b2:average): Average = {
B1.sum + = B2.sum
B1.count + = B2.count
B1
}
Transform the output of the reduction
def finish (reduction:average): Double = Reduction.sum.todouble/reduction.count
Specifies the Encoder for the intermediate value type
def bufferencoder:encoder[average] = encoders.product
Specifies the Encoder for the final output value type
def outputencoder:encoder[double] = encoders.scaladouble
}
}
Sparksql Basic Usage One