spark程序编写要点

本文介绍了Spark SQL编程的一些重要要点,包括导入functions包以便使用函数,避免join操作并利用window函数,详细说明了如何从csv文件中读取数据,以及SparkSession的启动方式。此外,还提到了获取DataFrame字段值的方法和关闭Spark连接的步骤。

1、import org.apache.spark.sql.functions._
sparksql中的函数需要引入这个包

2、尽量不适用join操作。推荐使用window窗口函数操作。
val resdf = sdf.withColumn(“age_avg”, avg(“weight”).over(Window.partitionBy(“sex”)))
.withColumn(“weight_min”, min(“weight”).over(Window.partitionBy(“sex”)))

3、spark2.x中 读入csv文件方法,其中option可以控制header首行是否当做模式读入
val sdf1 = spark.read.option(“header”, “true”).csv(“E:\traindata\ml-100k\test.csv”).toDF

4、printSchema()或 printSchema打印模式

5、sparksesson启动方式
val spark = SparkSession
.builder()
.appName(this.getClass.getName)
.master(“local[2]”)
.getOrCreate()

7、dataframe fildeIndex获取字段对应的值

8、spark.close()

9、根据模式生成dataframe的方法

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

// Create an RDD
val peopleRDD = spark.sparkContext.textFile("examples/src/main/resources/people.txt")

// The schema is encoded in a string
val schemaString = "name age"

// Generate the schema based on the string of 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 peopleDF = spark.createDataFrame(rowRDD, schema)

// Creates a temporary view using the DataFrame
peopleDF.createOrReplaceTempView("people")

// SQL can be run over a temporary view created using DataFrames
val results = spark.sql("SELECT name FROM people")

// The results of SQL queries are DataFrames and support all the normal RDD operations
// The columns of a row in the result can be accessed by field index or by field name
results.map(attributes => "Name: " + attributes(0)).show()
// +-------------+
// |        value|
// +-------------+
// |Name: Michael|
// |   Name: Andy|
// | Name: Justin|
// +-------------+
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值