大数据-Spark SQL

本文介绍 SparkSQL 的核心功能,包括创建 DataFrame 和 DataSet 的多种方式,以及如何使用 SQL 语句和 DSL 进行数据操作。此外,还展示了如何创建视图、进行多表查询,并使用不同的数据源。

Spark SQL

Spark SQL是Spark的一个模块,处理结构化数据,不能处理非结构化数据

特点

  • 容易集成(不需要单独安装)
  • 统一的数据访问方式(结构化数据的类型:JDBC、Json、Hive、Parquer文件都可以做为Spark SQL的数据源)
  • 完全兼容Hive(把Hive中的数据,读取到Spark SQL中运行)
  • 支持标准的数据连接

创建DataFrame

一、通过case class方式创建

grade.txt文件

06140411	Mr.Wu	102	110	106	318
06140407	Mr.Zhi	60	98	80	238
06140404	Mr.Zhang	98	31	63	192
06140403	Mr.Zhang	105	109	107	321
06140406	Mr.Xie	57	87	92	236
06140408	Mr.Guo	102	102	50	254
06140402	Mr.Li	54	61	64	179
06140401	Mr.Deng	83	76	111	270
06140409	Mr.Zhang	70	56	91	217
06140412	Mr.Yao	22	119	112	253
06140410	Mr.Su	45	65	80	190
06140405	Mr.Zheng	79	20	26	125

scala代码

# 定义schema
case class info(studentID: String,studentName: String,chinese: Int,math: Int,english: Int,totalGrade: Int)
val rdd = sc.textFile("/root/grade.txt").map(_.split("\t"))
val rdd1 = rdd.map(x => info(x(0),x(1),x(2).toInt,x(3).toInt,x(4).toInt,x(5).toInt))
val df = rdd1.toDF
df.show

结果

+---------+-----------+-------+----+-------+----------+                         
|studentID|studentName|chinese|math|english|totalGrade|
+---------+-----------+-------+----+-------+----------+
| 06140411|      Mr.Wu|    102| 110|    106|       318|
| 06140407|     Mr.Zhi|     60|  98|     80|       238|
| 06140404|   Mr.Zhang|     98|  31|     63|       192|
| 06140403|   Mr.Zhang|    105| 109|    107|       321|
| 06140406|     Mr.Xie|     57|  87|     92|       236|
| 06140408|     Mr.Guo|    102| 102|     50|       254|
| 06140402|      Mr.Li|     54|  61|     64|       179|
| 06140401|    Mr.Deng|     83|  76|    111|       270|
| 06140409|   Mr.Zhang|     70|  56|     91|       217|
| 06140412|     Mr.Yao|     22| 119|    112|       253|
| 06140410|      Mr.Su|     45|  65|     80|       190|
| 06140405|   Mr.Zheng|     79|  20|     26|       125|
+---------+-----------+-------+----+-------+----------+

在这里插入图片描述

二、通过spark session方式创建

grade.txt文件

06140411	Mr.Wu	102	110	106	318
06140407	Mr.Zhi	60	98	80	238
06140404	Mr.Zhang	98	31	63	192
06140403	Mr.Zhang	105	109	107	321
06140406	Mr.Xie	57	87	92	236
06140408	Mr.Guo	102	102	50	254
06140402	Mr.Li	54	61	64	179
06140401	Mr.Deng	83	76	111	270
06140409	Mr.Zhang	70	56	91	217
06140412	Mr.Yao	22	119	112	253
06140410	Mr.Su	45	65	80	190
06140405	Mr.Zheng	79	20	26	125

scala代码

import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
# 定义schema
val mySchema = StructType(List(StructField("studentID",DataTypes.StringType),StructField("studentName",DataTypes.StringType),StructField("chinese",DataTypes.IntegerType),StructField("math",DataTypes.IntegerType),StructField("english",DataTypes.IntegerType),StructField("totalGrade",DataTypes.IntegerType)))
val rdd = sc.textFile("/root/grade.txt").map(_.split("\t"))
val rdd1 = rdd.map(x => Row(x(0),x(1),x(2).toInt,x(3).toInt,x(4).toInt,x(5).toInt))
val df = spark.createDataFrame(rdd1,mySchema)
df.show

结果
在这里插入图片描述

三、读取带格式的文件

student.json文件

{"studentID":"06140401", "studentName":"Mr.Deng"}
{"studentID":"06140402", "studentName":"Mr.Li"}
{"studentID":"06140403", "studentName":"Mr.Zhang"}
{"studentID":"06140404", "studentName":"Mr.Zhang"}
{"studentID":"06140405", "studentName":"Mr.Zheng"}
{"studentID":"06140406", "studentName":"Mr.Xie"}
{"studentID":"06140407", "studentName":"Mr.Zhi"}
{"studentID":"06140408", "studentName":"Mr.Guo"}
{"studentID":"06140409", "studentName":"Mr.Zhang"}
{"studentID":"06140410", "studentName":"Mr.Su"}
{"studentID":"06140411", "studentName":"Mr.Wu"}
{"studentID":"06140412", "studentName":"Mr.Yao"}

scala代码

val df = spark.read.json("/root/temp/student.json")
val df = spark.read.format("json").load("/root/temp/student.json")
df.show

结果
在这里插入图片描述

操作DataFrame

DSL语句

df1.select($"studentName",$"chinese",$"math",$"english",$"totalGrade").show

在这里插入图片描述

df1.filter($"totalGrade">300).show

在这里插入图片描述

df1.groupBy($"roomID").count.show

SQL语句

grade表

在这里插入图片描述
student表

在这里插入图片描述
创建视图

df1.createOrReplaceTempView("grade")
df2.createOrReplaceTempView("student")
spark.sql("select studentID,totalGrade from grade").show

在这里插入图片描述

spark.sql("select count(*) as studentNum from student").show

在这里插入图片描述
多表查询(内连接)

spark.sql("select studentName,totalGrade from grade,student where grade.studentID = student.studentID order by grade.studentID").show

在这里插入图片描述

Spark SQL的视图

createGlobalTempView、createOrReplaceGlobalTempView、createOrReplaceTempView、createTempView

(1)普通视图(本地视图):只在当前Session中有效(createOrReplaceTempView、createTempView)

(2)全局视图:在不同的Session中都有用。原理:把全局视图创建在命名空间中:global_temp中(类似于一个库)(createOrReplaceTempView、createTempView)

创建DataSet

一、使用序列

scala代码
case class Person(name: String,age: Int)
val rdd = Seq(Person("destiny",18),Person("freedom",20)).toDF
rdd.show

结果
在这里插入图片描述

二、使用JSON数据

case class Student(studentID: String,studentName: String)
val df = spark.read.format("json").load("/root/temp/student.json")
df.as[Student].show

结果
在这里插入图片描述

三、使用其它格式数据

val ds = spark.read.text("/root/temp/spark_workCount.txt").as[String]
val word = ds.flatMap(_.split(" ")).filter(_.length > 3)
word.show

结果
在这里插入图片描述

val word = ds.flatMap(_.split(" ")).map((_,1)).groupByKey(_._1).count

结果
在这里插入图片描述

操作DataSet

ds.where($"totalGrade" >= 250).show

在这里插入图片描述
多表查询

case class Grade(studentID: String,chinese: Int,math: Int,english: Int,totalGrade: Int)
case class Student(studentID: String,studentName: String)
val rdd = sc.textFile("/root/temp/gradeSheet.txt").map(_.split("\t"))
val ds1 = rdd.map(x => Grade(x(0),x(1).toInt,x(2).toInt,x(3).toInt,x(4).toInt)).toDS
val rdd = sc.textFile("/root/temp/studentSheet.txt").map(_.split("\t"))
val ds2 = rdd.map(x => Student(x(0),x(1))).toDS

在这里插入图片描述

ds1.join(ds2,"studentID").show

在这里插入图片描述

ds1.join(ds2,"studentID").where("totalGrade >= 250").show

在这里插入图片描述

使用数据源

load与save函数

scala代码
val ds = spark.read.load("/root/temp/users.parquet")
# save结果的文件为parquet类型
ds.select($"name",$"favorite_color").write.save("/root/temp/parquet")
val ds1 = spark.read.load("/root/temp/parquet")
ds1.show

结果
在这里插入图片描述
在这里插入图片描述

mode函数

df.write.mode("overwrite").save("/root/temp/parquet")

在这里插入图片描述

saveAsTable函数

df.select($"name").write.saveAsTable("table1")
spark.sql("select * from table1").show

在这里插入图片描述

option函数

支持schema合并

val df = sc.makeRDD(1 to 6).map(x => (x,x*2)).toDF("singel","double")
df.write.mode("overwrite").save("/root/temp/table/key=1")
val df1 = sc.makeRDD(7 to 10).map(x => (x,x*3)).toDF("single","triple")
df1.write.mode("overwrite").save("/root/temp/table/key=2")
val df2 = spark.read.option("mergeSchema",true).parquet("/root/temp/table")

结果
在这里插入图片描述

### 使用Spark进行军用大数据场景下的机器学习 #### Spark在军事领域的作用 在军事领域,数据量庞大且复杂,涵盖了情报分析、战场态势感知等多个方面。为了高效处理这些海量数据并从中提取有价值的信息,采用分布式计算框架成为必然选择。Spark作为一种快速高效的内存型迭代批处理引擎,在处理大规模结构化和非结构化数据集上表现出色[^1]。 #### 构建基于Spark的机器学习流程 构建一个完整的基于Spark平台上的机器学习工作流通常涉及以下几个环节: - **数据收集预处理** 需要先从各种源(如卫星影像、雷达信号等)获取原始数据,并对其进行清洗、去噪以及特征工程等一系列操作,确保输入给后续模型训练阶段的数据质量良好。 - **模型选择训练** 根据具体任务需求挑选合适的算法库MLlib来进行监督或无监督的学习任务。例如可以利用决策树分类器预测敌方行动模式;或者运用K-means聚类发现潜在威胁目标群体特性。 - **评估调优** 对已建立好的模型性能进行全面评测,调整超参数直至获得最佳效果为止。此过程中可能还会涉及到交叉验证等高级技巧的应用。 - **部署上线** 将经过充分测试后的成品发布至生产环境当中投入使用,同时也要做好监控维护措施以便及时响应可能出现的问题。 ```python from pyspark.ml import Pipeline from pyspark.ml.classification import RandomForestClassifier from pyspark.ml.feature import StringIndexer, VectorAssembler from pyspark.sql import SparkSession spark = SparkSession.builder.appName('MilitaryDataAnalysis').getOrCreate() # 加载样本数据集 data = spark.read.csv('/path/to/military_dataset', header=True, inferSchema=True) # 特征向量化组装 assembler = VectorAssembler(inputCols=['feature_1', 'feature_2'], outputCol='features') # 类别标签索引映射 label_indexer = StringIndexer(inputCol='target_label', outputCol='indexedLabel') # 定义随机森林分类器作为核心组件之一 rf_classifier = RandomForestClassifier(labelCol="indexedLabel", featuresCol="features") # 创建管道对象串联各个步骤 pipeline = Pipeline(stages=[assembler, label_indexer, rf_classifier]) # 训练模型 model = pipeline.fit(data) # 序列化保存训练成果供日后加载重用 model.save("/tmp/random_forest_model") ``` 上述代码片段展示了如何使用PySpark API创建一条简单的流水线用于解决二元分类问题。实际应用中还需考虑更多细节因素比如异常检测机制的设计等等。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值