SparkOnHive本地运行访问hive(IDEA)
1. 添加依赖
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-hive_2.11</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
2. 配置文件
hive-site.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://192.168.60.66:3306/hivedb?createDatabaseIfNotExist=true</value>
<description>JDBC connect string for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>com.mysql.jdbc.Driver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.option.ConnectionUserName</name>
<value>bigdata</value>
<description>username to use against metastore database</description>
</property>
<property>
<name>javax.jdo.option.ConnectionPassword</name>
<value>123456</value>
<description>password to use against metastore database</description>
</property>
</configuration>
把hive-site.xml拷贝到Rsource目录下,如下图:
3. 对hive中的表进行读写操作示例
object SparkOnHiveDemo {
def main(args: Array[String]): Unit = {
//此时又可能会报权限不足的错
//org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException): Permission denied:
//需要在代码首行添加用户名
System.setProperty("HADOOP_USER_NAME", "xxx")
val ss = SparkSession
.builder()
.setAppName("SparkOnHiveDemo")
.setMaster("local[*]")
.enableHiveSupport()
.getOrCreate()
import ss.implicits._
//ss.sql("use spark001")
//使用 hive的insert 语句
ss.sql("CREATE TABLE IF NOT EXISTS spark001.tb001 (
id string,
name string
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\u0005'
COLLECTION ITEMS TERMINATED BY '\u0002'
MAP KEYS TERMINATED BY '\u0003'
STORED AS TEXTFILE;")
ss.sql("insert into table tb001 values (5,'yy')")
ss.sql("select * from tb001").show()
}
}