您的位置:首页 > 大数据 > Hadoop

Spark兼容Hive入门解析

2016-05-21 22:46 441 查看
最近使用spark兼容hive进行开发,所以静下心来简易的看了一遍。个人感觉有关与技术学习去官网是最正确的选择。所以我从官方网站入手开始讲,其他详细内容我不做过多介绍,这里直接开门见山。

官方网站有如下两点很重要:

Spark SQL also supports reading and writing data stored in Apache Hive. However, since
Hive has a large number of dependencies, it is not included in the default Spark assembly. Hive support is enabled by adding the 
-Phive
 and 
-Phive-thriftserver
 flags
to Spark’s build. This command builds a new assembly jar that includes Hive. Note that this Hive assembly jar must also be present on all of the worker nodes, as they will need access to the Hive serialization and deserialization libraries (SerDes) in order
to access data stored in Hive.

spark sql同样可以支持读取并且写入到hive中数据。然而,由于hive拥有许多依赖,hive并没有被包含在默认的组件里面。hive插件可以通过增加-Phive 和 -Phive-thriftserver 标签在你build本spark的时候。这个build命令会产生一个新的插件包含hive。注意,这个hive控件包必须被放在所有的worker的节点下,因为他们需要hive序列化和反序列化(SerDes)的权限从而获得拿取存储在hive中数据的权限。

Configuration of Hive is done by placing your 
hive-site.xml
core-site.xml
 (for
security configuration), 
hdfs-site.xml
 (for HDFS configuration)
file in 
conf/
. Please note when running the query on a YARN cluster (
cluster
 mode),
the 
datanucleus
 jars under the 
lib
 directory
and 
hive-site.xml
 under 
conf/
 directory
need to be available on the driver and all executors launched by the YARN cluster. The convenient way to do this is adding them through the 
--jars
 option
and 
--file
 option of the 
spark-submit
 command.

配置hive需要把你的hive-site.xml,core-site.xml,hdfs-site.xml 放入到你的conf/文件夹下面。注意,当你在yarn的集群上运行查询(命令)的时候,存放在lib目录下的datanucleus的jar包以及存放在conf下的hive-site.xml 配置文件需要对driver以及所有的yarn集群启动的executors有效。最简单的方式就是通过加入--jar
和--file操作在spark-submit命令中。

以上是官方的解释[我其实很不明白csdn赋值内容为什么总在一行,自己调格式很难看],那么我本地进行了一下实验。首先我这里假设你已经具备了上述的所有条件,我的spark的conf、lib文件夹如下:





这里的hdfs-site.xml、core-site.xml 是从hadoop的配置文件中传过来的,而hive-site.xml文件是从hive的配置文件中传过来的。那么我们启动我们的hdfs、spark、mysql,具体操作我不解释。spark的启动后,我们使用如下命令进入shell中:

bin/spark-shell \
--master spark://sun:7077 \
--executor-memory 1g \
--total-executor-cores 2 \
--driver-class-path /home/hadoop/app/spark1.6/lib/mysql-connector-java-5.1.35-bin.jar
这里简单介绍一下,第二列是指定我的spark的master节点所在,第三列指的是我为每个executor分配多大内存,记住是每个。第四列指的是我总共分配多少个内核,最后一个指定mysql的驱动包所在。

启动后我们进入spark的shell命令窗口。在命令窗口中我们使用如下命令:

import org.apache.spark.sql.hive.HiveContext
val hiveContext = new HiveContext(sc)
此时我们已经成功的连接到hive上,如何证明我们确实已经可以使用spark-hive了呢。我们来查看一下hive在mysql表中的所有表格信息,如下图所示:



工作空间有些杂乱,大家不必关系这里有什么表,只要记住这里没有person表,因为接下来我就要创建person的表,此时我在spark的shell中创建表格:

hiveContext.sql("create table person(id int,name varchar(20),age int)")
运行完毕后,我们查看mysql表格,如下:



没毛病,person表已经加入,我们查看hdfs,person表格也已经出现,如下图:



这样说明我们spark兼容hive已经可以使用,更多详细内容大家可以上spark官方网站查看,好了,到此关于spark兼容hive入门介绍就到此为止了。
感谢开源,让技术的大门向你我展开。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spark hive hdfs