博客
关于我
spark1.6使用:读取本地外部数据,把RDD转化成DataFrame,保存为parquet格式,读取csv格式
阅读量:526 次
发布时间:2019-03-07

本文共 1435 字,大约阅读时间需要 4 分钟。

Hadoop和Spark操作指南

启动Hadoop和Spark是数据处理的基础,以下步骤将帮助您顺利完成操作。

启动Spark

在终端中输入以下命令启动Spark:

spark-shell --master local[2] --jars /usr/local/src/spark-1.6.1-bin-hadoop2.6/libext/com.mysql.jdbc.Driver.jar

这一步需要确保Spark及其依赖已经正确安装,特别是若链接到MySQL数据库,必须添加对应的JAR。

读取Spark日志

将Spark目录下的日志文件读取进来进行测试:

val alllog=sc.textFile("file:///usr/local/src/spark-1.6.1-bin-hadoop2.6/logs/*out*")

验证记录数量:

alllog.count

注意:记得检查所选日志目录路径是否正确。

将 RDD转换为DataFrame

将读取到的RDD格式数据转换为DataFrame:

import org.apache.spark.sql.Rowval alllogRDD = alllog.map(x => Row(x))import org.apache.spark.sql.types._val schemaString = "line"val schema = StructType(  schemaString.split(" ").map(fieldName => StructField(fieldName, StringType(), true)))val alllogDataFrame = sqlContext.createDataFrame(alllogRDD, schema)

注册表并打印Schema:

alllogDataFrame.registerTempTable("log")alllogDataFrame.printSchema

显示DataFrame内容:

alllogDataFrame.show(false)

使用SQL查询

将DataFrame转换为临时表后,便可以使用SQL查询:

sqlContext.sql("SELECT * FROM log").show()

此时可以对表进行增删改查操作,方便数据处理。

读取与存储外部数据源

读取JSON文件

读取特定文件夹下的JSON文件:

val df = sqlContext.read.format("json").load("file:///mnt/hgfs/vm/china.json")df.printSchema

保存结果:

df.select("*").write.format("parquet").mode("overwrite").save("file:///mnt/hgfs/vm/china.parquet")

处理嵌套数组

对于包含嵌套数组的JSON文件,可以使用SQL的explode函数展开数据:

val exploded_df = sqlContext.sql("SELECT explode(array_column, ',') as column, value FROM parquet.`examples/src/main/resources/users.parquet`")exploded_df.show(false)

转载地址:http://osmjz.baihongyu.com/

你可能感兴趣的文章
Python读写json文件的简单实现
查看>>
Python 中的线程
查看>>
Python 中的继承机制是什么样的?
查看>>
python读写excel之xlrd&xlwt&xlutils组合
查看>>
Python 中的装饰器是什么?
查看>>
Python 中的装饰器是如何工作的,有哪些实际应用场景?
查看>>
python读excel
查看>>
Python 中读取 CSV 文件-ChatGPT4o作答
查看>>
Python 之 filecmp
查看>>
python请求html_使用Python请求获取HTML?
查看>>
Python 之匿名函数和偏函数
查看>>
python 之栈的实现
查看>>
python语音播放
查看>>
python语言:装饰器原理
查看>>
Python 交互式数据可视化详解
查看>>
python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
查看>>
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>
Python 优化提速的 8 个小技巧
查看>>