大数据学习
bigdata learning
Toggle navigation
大数据学习
主页
openGauss数据库
Flume
MongoDB
Hadoop
数据库实验
Kafka
Zookeeper
Hbase
Manual
Spark
Neo4j
InfluxDB
RabbitMQ
Flink
About Me
归档
标签
03-Spark-SparkSQL
无
2023-04-24 13:04:29
35
0
0
bigdata
## Spark SQL 和 DataFrames Spark SQL 是 Spark 内嵌的模块,用于结构化数据。在 Spark 程序中可以使用 SQL 查询语句或 [DataFrame API](http://spark.apache.org/docs/latest/sql-programming-guide.html)。DataFrames 和 SQL 提供了通用的方式来连接多种数据源,支持 Hive、Avro、Parquet、ORC、JSON、和 JDBC,并且可以在多种数据源之间执行 join 操作。 使用 SQLContext 可以从现有的 RDD 或数据源创建 DataFrames。作为示例,我们通过 Spark 提供的 JSON 格式的数据源文件 ./examples/src/main/resources/people.json 来进行演示,该数据源内容如下: ```json {"name":"Michael"} {"name":"Andy", "age":30} {"name":"Justin", "age":19} ```  执行如下命令导入数据源,并输出内容: ```scala scala> val df = spark.read.json("file:///usr/local/spark/examples/src/main/resources/people.json") df: org.apache.spark.sql.DataFrame = [age: bigint, name: string] scala> df.show() +----+-------+ | age| name| +----+-------+ |null|Michael| | 30| Andy| | 19| Justin| +----+-------+ ``` >其中spark对象,是在启动进入spark-shell以后,spark-shell默认提供的Spark-Session对像。 接着,我们来演示 DataFrames 处理结构化数据的一些基本操作: ```json scala> df.select("name").show() // 只显示 "name" 列 +-------+ | name| +-------+ |Michael| | Andy| | Justin| +-------+ scala> df.select(df("name"), df("age") + 1).show() // 将 "age" 加 1 +-------+---------+ | name|(age + 1)| +-------+---------+ |Michael| null| | Andy| 31| | Justin| 20| +-------+---------+ scala> df.filter(df("age") > 21).show() //条件语句 +---+----+ |age|name| +---+----+ | 30|Andy| +---+----+ scala> df.groupBy("age").count().show() // groupBy 操作 +----+-----+ | age|count| +----+-----+ | 19| 1| |null| 1| | 30| 1| +----+-----+ ``` 当然,我们也可以使用 SQL 语句来进行操作: ```scala scala> df.registerTempTable("people") // 将 DataFrame 注册为临时表 people warning: there was one deprecation warning; re-run with -deprecation for details scala> val result = spark.sql("SELECT name, age FROM people WHERE age >= 13 AND age <= 19") // 执行 SQL 查询 result: org.apache.spark.sql.DataFrame = [name: string, age: bigint] scala> result.show() // 输出结果 +------+---+ | name|age| +------+---+ |Justin| 19| +------+---+ ``` 更多的功能可以查看完整的 [DataFrames API](http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.DataFrame),此外 DataFrames 也包含了丰富的 [DataFrames Function](http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$)可用于字符串处理、日期计算、数学计算等。
上一篇:
03-Neo4j-CREATE命令
下一篇:
03-Zookeeper服务端集群搭建*
文档导航