博客
关于我
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/

你可能感兴趣的文章
PIESDKDoNet二次开发配置注意事项
查看>>
PIGS POJ 1149 网络流
查看>>
PIL Image对图像进行点乘,加上常数(等像素操作)
查看>>
PIL Image转Pytorch Tensor
查看>>
PIL&QOOT;IOERROR:带有大图像的图像文件被截断(&Q)
查看>>
PIL.Image、cv2的img、bytes相互转换
查看>>
PIL.Image进行图像融合显示(Image.blend)
查看>>
pilicat-dfs 霹雳猫-分布式文件系统
查看>>
Pillow lacks the JPEG 2000 plugin
查看>>
SpringBoot之ElasticsearchRestTemplate常用示例
查看>>
ping 全网段CMD命令
查看>>
ping 命令的七种用法,看完瞬间成大神
查看>>
Pinia入门(快速上手)
查看>>
Pinia:$patch的使用场景
查看>>
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>