准备条件:
部署hadoop集群
部署spark集群
安装python(本人安装的是anaconda3,python是3.6)
配置环境环境变量:
vi .bashrc #添加如下内容 export SPARK_HOME=/opt/spark/current export PYTHONPATH=$SPARK_HOME/python/:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip
ps:spark里面会自带一个pyspark模块,但是本人官方下载的 spark2.1中的pyspark 与 python3.6 不兼容,存在bug,如果看官用的也是 python3的话,建议到githup下载最新的 pyspark 替换掉$SPARK_HOME/python目录下面的pyspark。
开启打怪升级:
1.启动hadoop集群和spark集群
2.将数据传到hadoop文件系统上,people.json是官方提供的案例数据,salary.json是本人自己新建的数据
hadoop fs -mkdir -p /user/hadoop/examples/src/main/resources/ hadoop fs -put people.json /user/hadoop/examples/src/main/resources/ hadoop fs -put salary.json /user/hadoop/examples/src/main/resources/
3.编写python SparkSQL程序
# -*- coding: utf-8 -*- """ Created on Wed Feb 22 15:07:44 2017 练习SparkSQL @author: wanghuan """ from pyspark.sql import SparkSession spark = SparkSession.builder.master("spark://cent0s7Master:7077").appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value") .getOrCreate() #ssc=SparkContext("local[2]","sparksqltest") peopleDF = spark.read.json("examples/src/main/resources/people.json") salaryDF = spark.read.json("examples/src/main/resources/salary.json") #peopleDF.printSchema() # Creates a temporary view using the DataFrame peopleDF.createOrReplaceTempView("people") salaryDF.createOrReplaceTempView("salary") # SQL statements can be run by using the sql methods provided by spark teenagerNamesDF = spark.sql("SELECT a.name,a.age,b.salary FROM people a,salary b where a.name=b.name and a.age <30 and b.salary>5000") teenagerNamesDF.show()
4.运行SparkSQL 应用
运行花了42秒(这个执行时间我觉得有点长,应该跟本人虚拟机性能不咋地相关,本人就是个dell笔记本跑四个虚拟机),结果出来了, 19岁的Justin工资就到了10000了,真是年轻有为呀。
ps:本人原打算是用java或者scala来开发spark应用的,但是,配置开发环境真的是心酸的历程,最麻烦的是scala的编译环境,sbt或者maven下载很多包,国外的包下载不下来(原因大家都懂的)。我只能转而用解释性的python来编写了,至少不用下载国外的编译包了。
原文地址:http://wongsong.blog.51cto.com/6040075/1905190