配色: 字号:
01-Hive2_Hive说明、Hive schema及仓库配置、表分类、客户端连接Hive、Hive命令、Hive数据类型
2022-09-15 | 阅:  转:  |  分享 
  
Hive元数据配置、表分类、连接方式、常用命令、数据类型2018-04-13版本修改人修改记录修改时间V1.0王守奎编写2018/4/13目
录背景5简介5Hiveschema到Mysql配置5Hive数据仓库的默认位置配置6Hive表分类6托管表(内部表)6外部表7
分区表7常见问题9Hive连接配置9HiveService2配置10HivewebUI配置11HiveHA配置12Jdbc连接
Hive18Beeline客户端可以实现远程的jdbc连接24Treesoftweb客户端26squirrel-sql客户端26
Hue客户端31Hive常用操作命令31[查看HDFS信息]31[Hive清屏操作]32[直接在操作系统运行语句]32[执行一个文
件(存储HQL语句),通常用于批处理]32[显示所有的命令]33[显示comment]33[显示字段名称,时效当前会话]33[创建
DB]34[显示db,描述信息,不包含扩展信息]34[存在即删除,如果有表数据无法删除]35[级联删除表信息]35[创建DB并指定
存储的位置]35[使用库]36[创建表并指定表属性信息]36[创建表并指定HDFS的存储位置]36[显示表扩展信息]36[使用格式
化的形式显示信息]36[复制表:包括表结果和数据]36[复制表:只负责表结构,没有数据]37[创建表]37[加载数据,覆盖原来数据
]38[加载数据,追加数据]38[导出数据,覆盖原有数据]38[导出数据到多个目录]38Hive数据单元39Hive数据类型39基
本类型39集合类型39背景Hive在搭建完成之后,具体的元数据、大数据仓库存储、表分类、连接方式和数据类型需要有一定认识,本文具体
介绍如上的知识点,供以后工作需要参考。简介数据仓库:OLAP,分析处理,存储和分析,延迟较高。数据库:OLTP,在线事务处理,低延
迟,事务支持。Hive属于数据仓库,运行在hadoop上,类sql方式运行,sql(hiveql,hql),mr运算。Hive操作
结构化数据,schema(模式,元信息存放到数据库中),数据存放在hdfs文件中,数据库和表都是以路径的形式存储于HDFS。Hiv
eschema到Mysql配置Hiveschema默认数据库Derby同一时刻只能有一个连接,无法满足实际生产的需要,所以需要
将Hiveschema数据存储于mysqldb以满足实际业务场景的需求。修改hivescheam存储的步骤如下:1、修改
hive-site.xml,添加mysql连接信息[/soft/hive/conf/hive-site.xml]y>javax.jdo.option.ConnectionDriverNamecom.
mysql.jdbc.Driver
javax.jdo.
option.ConnectionURL
jdbc:mysql://localhost:3306/my
hive
roperty>javax.jdo.option.ConnectionUserName
root
javax.jdo.option.ConnectionPassword
root
在mysql中建立myhive数据库(mysql和hi
ve在不同的主机部署需要授权操作)$>mysql>createdatabasemyhive;//建立hive库$>mysq
l>grantallprivilegesonmyhive.toroot@''192.168.35.179''ident
ifiedby''root'';$>mysql>flushprivileges;3、mysql驱动程序(jar)放到hivec
lasspath下[注意驱动程序与mysql数据库的匹配]/soft/hive/lib/mysql-connector-java-
5.0.8.jar4、重新初始化hiveschema元数据库$>/soft/hive/bin/schematool-initS
chema--dbTypemysql执行完成后会发现mysql的myhive库中有了元数据相关的表,如下图所示:Hive数据
仓库的默认位置配置修改[hive-site.xml],配置如下的信息【根据自己的需要制定位置】表示数据在hdfs中的存储位置。hi
ve.metastore.warehouse.dir=/user/hive/warehouseHive表分类托管表(内部表)hiv
e默认创建的表都是托管表,hive控制其数据的生命周期。删除托管表时,元数据和数据均被删除。createtableifnot
existsmyhive.employee_inner(eidint,nameString,salaryString
,destinationString)COMMENT''Employeedetails''ROWFORMATDELIM
ITEDFIELDSTERMINATEDBY''\t''LINESTERMINATEDBY''\n''STOREDAS
TEXTFILE;droptableemployee_inner;外部表hive控制元数据,删除外部表时,数据不被删除。重新
建立表结构信息还可以恢复数据查询。createexternaltableifnotexistsmyhive.emplo
yee_external(eidint,nameString,salaryString,destinationStr
ing)COMMENT''Employeedetails''ROWFORMATDELIMITEDFIELDSTERMI
NATEDBY''\t''LINESTERMINATEDBY''\n''STOREDASTEXTFILE;dropta
blemyhive.employee_external;分区表分区表本质还是托管表,用于在数据较多时,可以根据指定的条件进行分类
存储。[创建分区表]createtableifnotexistsmyhive.test2(eidint,nameS
tring,salaryString,destinationString)partitionedby(country
string,statestring)ROWFORMATDELIMITEDFIELDSTERMINATEDBY''\
t''LINESTERMINATEDBY''\n''STOREDASTEXTFILE;[加载数据到指定分区]loadda
talocalinpath''/home/hadoop/Desktop/employee.txt''intotablemy
hive.test2partition(country=''china'',state=''shanxi'');[查看hdfs]hdfs
dfs-ls-R//user/hive/warehouse/myhive.db/test2/country=china/s
tate=shanxi/employee.txt[查询数据]selectfrommyhive.test2whereco
untry=''china''andstate=''shanxi'';[分区表的查询模式:strict/nostrict]sethi
ve.mapred.mode=strict//严格模式,默认是非严格,严格模式要求查询的时候必须带分区,临时设定。[查看分区表有那
些分区]showpartitionsmyhive.test2;[查看具体分区的细节信息]showpartitionsmyh
ive.test2partition(state=''shanxi'');[查看扩展信息]descextendedmyhive
.test2;[手动增加分区,不能增加不存在的分区列]altertablemyhive.test2addpartitio
n(country=''china'',state=''henan'')[删除分区]Altertablemyhive.test2
droppartition(country=''china'',state=''henan'');[修改表,重命名]altertab
lemyhive.test2renametomyhive.test1[添加多个分区]altertablemyhive
.test1addpartition(country=''china'',state=''hubei'')partition(cou
ntry=''china'',state=''hebei'')partition(country=''china'',state=''sha
ndong'');[移动分区位置,新数据加入到新目录下(旧有的数据无法跟随)]altertablemyhive.test1pa
rtition(country=''china'',state=''hubei'')setlocation''/user/hive/w
arehouse/myhive.db/test1/country=china/state=hubei1'';[增加列]alter
tablemyhive.test1addcolumns(birthstring,firestring)[修改或者删除,操
作后仅剩下括弧汇中的字段]altertabletest1replacecolumns(birthint);[复制数据到
分区表][创建表test2]createtableifnotexistsmyhive.test2(eidint,na
meString,salaryString,destinationString)partitionedby(coun
trystring,statestring)ROWFORMATDELIMITEDFIELDSTERMINATEDB
Y''\t''LINESTERMINATEDBY''\n''STOREDASTEXTFILE;[创建表test3]cre
atetableifnotexistsmyhive.test3(eidint,nameString,salary
String,destinationString)partitionedby(countrystring,state
string)ROWFORMATDELIMITEDFIELDSTERMINATEDBY''\t''LINESTERM
INATEDBY''\n''STOREDASTEXTFILE;[整表复制,注意字段个数要相同,下方的语句无法导入数据]i
nsertintomyhive.test2partition(country=''china'',state=''henan'')
selectfrommyhive.test1;[字段个数要相同,查询时分区通过where子句指定。插入时,分区用part
ition指定]insertintomyhive.test3partition(country=''china'',state=
''hubei'')selecteid,name,salary,destinationfrommyhive.test2whe
recountry=''china''andstate=''henan'';常见问题1、Youhaveanerrorin
yourSQLsyntax;checkthemanualthatcorrespondstoyourMySQL
serverversionfortherightsyntaxtousenear''OPTIONSQL_SELE
CT_LIMIT=DEFAULT''atline1方案:hive使用的mysql驱动版本和mysql数据库不匹配,使用适合的或
高于mysql版本的驱动即可。2、Loadingclass`com.mysql.jdbc.Driver''.Thisisd
eprecated.Thenewdriverclassis`com.mysql.cj.jdbc.Driver''.方案
:在高版本的mysql数据库中的驱动名称已经替换为”com.mysql.cj.jdbc.Driver”。使用就的驱动名称也可以使用
。Causedby:com.mysql.cj.core.exceptions.InvalidConnectionAttribu
teException:Theservertimezonevalue''PDT''isunrecognizedor
representsmorethanonetimezone.Youmustconfigureeitherthe
serverorJDBCdriver(viatheserverTimezoneconfigurationprop
erty)touseamorespecifctimezonevalueifyouwanttoutiliz
etimezonesupport.方案:优化hive-site.xml中的数据库连接,增加如下的红色部分。y>javax.jdo.option.ConnectionURLjdbc:mysql:
//localhost:3306/myhive?serverTimezone=UTC
Hiv
e连接配置这里客户端指eclipse和beeline,客户端通过hiveserver2连接到Hive。所以运行前要保证hivese
rver2的开启。HiveService2配置HiveServer2可以支持多客户端并发和身份认证。旨在为开放API客户端(如JD
BC和ODBC)提供更好的支持。在生产环境中使用Hive,强烈建议使用HiveServer2来提供服务,好处很多:1.在应用端不
用部署Hadoop和Hive客户端;2.相比hive-cli方式,HiveServer2不用直接将HDFS和Metastore暴
漏给用户;3.有安全认证机制,并且支持自定义权限校验;4.有HA机制,解决应用端的并发和负载均衡问题;5.JDBC方式,可以
使用任何语言,方便与应用进行数据交互;6.从2.0开始,HiveServer2提供了WEBUI。默认参数配置,有需要时可以根据
自身的需求进行变更hive.server2.thrift.min.worker.threads–最小工作线程数,默认为5。hiv
e.server2.thrift.max.worker.threads–最小工作线程数,默认为500。hive.server2
.thrift.port–TCP的监听端口,默认为10000。hive.server2.thrift.bind.host–T
CP绑定的主机,默认为localhost。1、修改hive-site.xml的配置文件,使用操作系统的认证方式[/soft/hiv
e/conf/hive-site.xml]参数信息修改为如下配置hive.server2.enable.doAs=falsehiv
e.metastore.sasl.enabled=falsehive.server2.authentication=NONE参数功
能介绍hive.server2.enable.doAstrue<
/value>SettingthispropertytotruewillhaveHiv
eServer2executeHiveoperationsastheusermakingthecallsto
it.默认情况下,HiveServer2以提交查询的用户执行查询(true),如果hive.server2.enable.doA
s设置为false,查询将以运行hiveserver2进程的用户运行。
<
property>hive.metastore.sasl.enabledfalsevalue>Iftrue,themetastoreThriftinterfacewillb
esecuredwithSASL.ClientsmustauthenticatewithKerberos.meta
storethrift接口的安全策略,开启则用SASL加密接口,客户端必须要用Kerberos机制鉴权,默认是不开启false;
hive.server2.authentic
ation
NONEExpectsoneof[no
sasl,none,ldap,kerberos,pam,custom].Clientauthenticationt
ypes.NONE:noauthenticationcheckLDAP:LDAP/ADbasedauthentic
ationKERBEROS:Kerberos/GSSAPIauthenticationCUSTOM:Customaut
henticationprovider(Usewithpropertyhive.server2.custom.authe
ntication.class)PAM:PluggableauthenticationmoduleNOSASL:Ra
wtransport
启动hiveserver2服务器启动Hiveserve
r2有两种方式,一种是hive--servicehiveserver2,另一种更为简洁,为hiveserver2。个人建议的方
式:nohuphiveserver2start&hiveserver2stop---------------------
-----------------------------3、hive--servicehiveserver2stop4
、nohuphive--servicehiveserver2start&HivewebUI配置vi$HIVE_HOM
E/conf/hive-site.xmlhive.server2.webui.hoste>namenodehive.serve
r2.webui.port
10002
在用浏览器访问http:
//namenode:10002页面之前,先启动HiveServer2、hdfs和Metastore服务。主页中显示了当前链接的
会话,包括IP、用户名、当前执行的操作(查询)数量、链接总时长、空闲时长;如果有会话执行查询,那么下面的Queries会显示查询的
语句、执行耗时等:HiveHA配置HiveServer2的多实例高可用-Ha配置完成,的确能解决生产中的很多问题,比如:并发、负
载均衡、单点故障、安全等等。如果使用HiveServer2的Client并发比较少,可以使用一个HiveServer2实例,没问题
。但如果这一个实例挂掉,那么会导致所有的应用连接失败。Hive从0.14开始,使用Zookeeper实现了HiveServer2的
HA功能(ZooKeeperServiceDiscovery),Client端可以通过指定一个nameSpace来连接Hive
Server2,而不是指定某一个host和port。如上图,我准备在node1和node2上分别启用两个HiveServer2的实
例,并通过zookeeper完成HA的配置。这里最主要的是利用了zk的命名空间,首先我们把两个hiserver2先后启动,注册到z
k集群的,然后通过zk轮询做高可用。注:这里假设你的Zookeeper已经安装好,并可用。第一步在两台节点上安装hive,除了配
置的ip不同,其他的都相同,并在hive-site.xml中添加如下配置。rty>hive.server2.support.dynamic.service.discoveryalue>true
hive.zookeepe
r.quorum
datanode1:2181,datanode2:2181,datanode3:21
81
hive.zookeeper
.client.port
2181
hive.se
rver2.thrift.bind.host
namenode
第二
步启动分别启动两个hiveserver2服务,确认端口是否监听netstat-lnp|grep10000,默认端口是1
0000。nohuphiveserver2start&第三步查看zk集群是否有了配置文件中的命名空间。通过如下的两种方式都可
以查看。第四步发起请求,命令如下JDBC连接的URL格式为:jdbc:hive2:///Name>;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserve
r2其中:为Zookeeper的集群链接串如datanode1:2181,datanode2
:2181,datanode3:2181为Hive数据库,默认为defaultserviceDiscoveryM
ode=zooKeeper指定模式为zooKeeperzooKeeperNamespace=hiveserver2指定ZK中的
nameSpace即参数hive.server2.zookeeper.namespace所定义,我定义为hiveserver2_z
k连接实例beeline-u"jdbc:hive2://datanode1:2181,datanode2:2181,datan
ode3:2181/hivedb;serviceDiscoveryMode=zooKeeper;zooKeeperNamespac
e=hiveserver2_zk"第五步在HA的任意一个主机通过beeline都可以进行hive操作。通过java代码连接也
都可以进行hive操作。packagecom.bm.bigData_hive;importjava.sql.Connectio
n;importjava.sql.DriverManager;importjava.sql.PreparedStatement
;importjava.sql.ResultSet;importjava.sql.SQLException;/Cop
yright(C)2018编码界的小菜鸟作者:王守奎2018年11月2日上午11:15:02/publ
icclassApp{publicstaticvoidmain(String[]args)throwsClass
NotFoundException,SQLException{Class.forName("org.apache.hive.jd
bc.HiveDriver");Connectionconn=DriverManager.getConnection("jd
bc:hive2://datanode1:2181,datanode2:2181,datanode3:2181/hive1;ser
viceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2_zk","
hadoop","hadoop");PreparedStatementppst=conn.prepareStatement
("selectfromtest1");ResultSetrs=ppst.executeQuery();while
(rs.next()){intid=rs.getInt("id");Stringname=rs.getString(
"name");intage=rs.getInt("age");System.out.println(id+","+
name+","+age);}rs.close();ppst.close();conn.close();}}第六步我们杀
掉其中一个hiveserver2,比如datanode1节点的hiveserver2,然后还可以请求,多次测试可以使用。杀掉一个进
程,zk注册的就少了一个。通过datanode1主机访问,还可以正常连接,但是自动连接到namendoe的hive了。通过第五步的
java代码访问,可以正常查询。当把namenode的hiveserver2服务也停止后,主机节点、java代码客户端均不可以连接
hive服务了。Jdbc连接Hive1、创建maven项目bigdata-hive-2.1.02、配置pom文件xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w
3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.ap
ache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><
modelVersion>4.0.0com.bmctId>bigData-hive0.0.1-SNAPSHOTackaging>jarbigData-hivehttp://mave
n.apache.org
UTF-8
ency>junitjuniton>4.12testupId>org.apache.hivehive-jdbc<
version>2.1.0
org.apac
he.hive
hive-service2.
1.0
3、修改app程序packa
gecom.bm.bigData_hive;importjava.sql.Connection;importjava.sql
.DriverManager;importjava.sql.PreparedStatement;importjava.sql.
ResultSet;importjava.sql.SQLException;/Copyright(C)2018编
码界的小菜鸟作者:王守奎2018年11月2日上午11:15:02/publicclassApp{pub
licstaticvoidmain(String[]args)throwsClassNotFoundException
,SQLException{Class.forName("org.apache.hive.jdbc.HiveDriver");
//Hive服务没有开启认证功能,所以用户名和密码随意Connectionconn=DriverManager.getCon
nection("jdbc:hive2://namenode:10000/hivedb","hadoop","hadoop")
;PreparedStatementppst=conn.prepareStatement("selectfromus
ers");ResultSetrs=ppst.executeQuery();while(rs.next()){inti
d=rs.getInt("id");Stringname=rs.getString("name");intage=
rs.getInt("age");System.out.println(id+","+name+","+age);
}rs.close();ppst.close();conn.close();}}测试增删改查准备工作packagecom.bm.
bigData_hive;importjava.sql.Connection;importjava.sql.DriverMan
ager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;
importjava.sql.SQLException;importorg.junit.Before;importorg.j
unit.Test;/Copyright(C)2018编码界的小菜鸟作者:王守奎2018年11月2日
上午11:17:12/publicclassTestCRUD{privateConnectionconn;/
连接hive数据库./@BeforepublicvoidiniConn()throwsException{Cla
ss.forName("org.apache.hive.jdbc.HiveDriver");//Hive服务没有开启认证功能,所
以用户名和密码随意conn=DriverManager.getConnection("jdbc:hive2://namenod
e:10000/hivedb","hadoop","hadoop");}}创建表@Testpublicvoidcreate
table()throwsSQLException{PreparedStatementppst=conn.prepar
eStatement("createtableusers(idint,namestring,ageint)");ppst
.execute();ppst.close();conn.close();System.out.println("创建表成功!")
;}批量插入数据@TestpublicvoidbatchInsert()throwsSQLException{Prepa
redStatementppst=conn.prepareStatement("insertintousers(id,n
ame,age)values(?,?,?)");ppst.setInt(1,1);ppst.setString(2,"tom
1");ppst.setInt(3,30);ppst.executeUpdate();ppst.setInt(1,2);pps
t.setString(2,"tom2");ppst.setInt(3,31);ppst.executeUpdate();pp
st.close();conn.close();}删除数据@Testpublicvoiddelete()throwsSQL
Exception{PreparedStatementppst=conn.prepareStatement("delete
fromusers");ppst.executeUpdate();ppst.close();conn.close();}Att
empttodoupdateordeleteusingtransactionmanagerthatdoesn
otsupporttheseoperations.不支持更新和删除操作聚合函数统计总数@Testpublicvoidco
unt()throwsSQLException{PreparedStatementppst=conn.prepareS
tatement("selectcount()fromusers");ResultSetrs=ppst.execut
eQuery();rs.next();System.out.println(rs.getInt(1));ppst.close();
conn.close();}删除表@Testpublicvoiddroptable()throwsSQLException
{PreparedStatementppst=conn.prepareStatement("droptableuser
s");ppst.execute();ppst.close();conn.close();}按需查询@Testpublicvoi
dquery()throwsSQLException{PreparedStatementppst=conn.prep
areStatement("selectfromuserswherename=''tom1''");ResultSetr
s=ppst.executeQuery();while(rs.next()){intid=rs.getInt(1);
Stringname=rs.getString(2);System.out.println(id+":"+name);}pp
st.close();conn.close();}Beeline客户端可以实现远程的jdbc连接hiveServer2?支持一个新
的命令行Shell,称为Beeline,它是基于SQLLineCLI的JDBC客户端。beeline的常用参数TheBeel
ineCLI支持以下命令行参数:OptionDescription--autoCommit=[true/false]
---进入一个自动提交模式:beeline--autoCommit=true--autosave=[true/false]
---进入一个自动保存模式:beeline--autosave=true--color=[true/false]---显
示用到的颜色:beeline--color=true--delimiterForDSV=DELIMITER---分隔值输出格
式的分隔符。默认是“|”字符。--fastConnect=[true/false]---在连接时,跳过组建表等对象:beeli
ne--fastConnect=false--force=[true/false]---是否强制运行脚本:beeline
--force=true--headerInterval=ROWS---输出的表间隔格式,默认是100:beeline-
-headerInterval=50--help---帮助beeline--help--hiveconfproperty
=value---设置属性值,以防被hive.conf.restricted.list重置:beeline--hivecon
fprop1=value1--hivevarname=value---设置变量名:beeline--hivevarv
ar1=value1--incremental=[true/false]---输出增量--isolation=LEVEL
---设置事务隔离级别:beeline--isolation=TRANSACTION_SERIALIZABLE--maxCol
umnWidth=MAXCOLWIDTH---设置字符串列的最大宽度:beeline--maxColumnWidth=25--
maxWidth=MAXWIDTH---设置截断数据的最大宽度:beeline--maxWidth=150--nullempt
ystring=[true/false]---打印空字符串:beeline--nullemptystring=false--
numberFormat=[pattern]---数字使用DecimalFormat:beeline--numberF
ormat="#,###,##0.00"--outputformat=[table/vertical/csv/tsv/dsv/c
sv2/tsv2]---输出格式:beeline--outputformat=tsv--showHeader=[true/fa
lse]---显示查询结果的列名:beeline--showHeader=false--showNestedErrs=[t
rue/false]---显示嵌套错误:beeline--showNestedErrs=true--showWarnings=
[true/false]---显示警告:beeline--showWarnings=true--silent=[true/fa
lse]---减少显示的信息量:beeline--silent=true--truncateTable=[true/fals
e]---是否在客户端截断表的列--verbose=[true/false]---显示详细错误信息和调试信息:beeline
--verbose=true-d---使用一个驱动类:beeline-ddriver_cla
ss-e---使用一个查询语句:beeline-e"query_string"-f---加
载一个文件:beeline-ffilepath多个文件用-efile1-efile2-n
---加载一个用户名:beeline-nvalid_user-p---加载一个密码:beeline-
pvalid_password-u---加载一个JDBC连接字符串:beeline-udb_
URL1、连接,使用如下命令之一进行连接beeline连接hive--servicebeeline-ujdbc:hiv
e2://namenode:10000/myhivebeeline-ujdbc:hive2://namenode:10000/
myhive2、在beeline中执行命令,命令基本同hive命令行操作一致[执行脚本]$>0:jdbc:hive2://nam
enode:10000/myhive>!shclear[查看库]$>0:jdbc:hive2://namenode:1000
0/myhive>showdatabases;[查看帮助]$>0:jdbc:hive2://namenode:10000/m
yhive>!help[连接到新的db]$>0:jdbc:hive2://namenode:10000/myhive>!conn
ectjdbc:hive2://namenode:10000/myhiveTreesoftweb客户端Treesoft可以在界
面进行sql运行和图形化的状态监控,适用的数据库如下。Treesoft为web应用下载完成直接部署到tomcat即可运行,登录界面
输入Hql即可运行。squirrel-sql客户端SQuirrelSQLClient是一个用Java写的数据库客户端,用JDB
C统一数据库访问接口以后,可以通过一个统一的用户界面来操作MySQLPostgreSQLMSSQLOracle等等任何支持J
DBC访问的数据库。使用起来非常方便。而且,SQuirrelSQLClient还是一个典型的Swing程序,也算是Swing的
一个比较成功的应用了。关于此工具的详细介绍还可以了解官方信息【http://www.squirrelsql.org/】,此工具的方
便之处在于,可能工作中一天会访问很多的数据库,有oracle、mysql、hive、hbase等不同种类的数据库,而每一种数据库都
是不一样的连接工具,而SQuirrelSQLClient的特性为jdbc的连接方式,所以配置好了相应的数据库的jdbc驱动就可
以访问所有的不同种类的数据库。接下来介绍怎么去配置hive驱动第一步,打开drivers驱动配置器,点击添加第二步,填写配置信息n
ame:可自定义命名exampleURL:HIVE存储在hdfs上的url第三步:在extraclasspath路径中ad
d一些关于hive的jara包,导入到extraclasspath中。classname与截图相同,点击ok,即可提示配置
成功的界面第四步,配置Aliases填写配置信息Name:自定义名称Driver:选择刚才配置好的驱动username:用户名p
assword:密码接下来就连接成功了,可以进行查询操作但是在连接hive的时候,建立的session隔一段时间就会断,所以需要设
置一个保持连接的参数,隔一段时间访问服务器一次,保持session的存活点击连接,选择到PropertiesHue客户端登录hue
web界面,在指定的文本框中输入sql语句运行即可。Hive常用操作命令Beeline和hive操作的命令使用方法一致,下方以be
eline为例展示。两种方法不一致时同时展示两种写法。[查看HDFS信息]dfs-ls-R/;[Hive清屏操作]!shc
lear[直接在操作系统运行语句]hive-e"selectfromhivedb.users"//-eexecut
ebeeline-ujdbc:hive2://namenode:10000/hivedb-e"selectfrom
hivedb.users"[执行一个文件(存储HQL语句),通常用于批处理][hive.hql]selectfromhiv
edb.users;hive-fhive.hqlbeeline-ujdbc:hive2://namenode:10000/
hivedb-fhive.hql[显示所有的命令]tabtab[显示comment]--thisisacommen
t[显示字段名称,时效当前会话]sethive.cli.print.header=true;//仅限hive命令行,beel
ine默认就有字段名称[创建DB]createdatabaseifnotexistsmyhive2;createdat
abasehive3withdbproperties(''author''=''wsk'',''createtime''=''today''
);alterdatabasehive3setdbproperties(''author''=''you'');[显示db,描述信
息,不包含扩展信息]desc[ribe]databasehive2;[显示db,描述信息,包含扩展信息]descdataba
seextendedhive3;[存在即删除,如果有表数据无法删除]dropdatabaseifexistshive
3;[级联删除表信息]dropdatabaseifexistshive3cascade;[创建DB并指定存储的位置]
createdatabasehive2location''/user/hadoop/hive2'';[使用库]usehive
3;[创建表并指定表属性信息]createtablehive6.test1(idint,namestring,agein
t)tblproperties(''author''=''you'');[创建表并指定HDFS的存储位置]createtablehi
ve1.test2(idint,namestring,ageint)location''/user/hadoop/test
2'';[显示表扩展信息]descextendedhive1.test1;[使用格式化的形式显示信息]descformat
tedmyhive.test1;[修改表的属性(查看descformattedtablenametablepa
rameters)]altertabletablenamesettblproperties(''comment''=''xxxx
xxx'');[修改分隔符]修改分隔符(无分区):altertabletablenamesetserdepropertie
s(''field.delim''?=?''\t'');修改分隔符(有分区):altertabletablenameparti
tion(dt=''20160916'')?setserdeproperties(''field.delim''?=?''\t'');
[内部表与外部表转换]altertabletablenamesettblproperties(''external''=
''true'');//内部表转外部表?altertabletablenamesettblproperties(''extern
al''=''false'');//外部表转内部表[复制表:包括表结果和数据]createtablehive2.usersas
selectfromhivedb.users;[复制表:只负责表结构,没有数据]createtablehive2.
user2likehivedb.users;createexternaltablehive2.test7likeh
ivedb.users;[显示指定数据库的表集合,默认是当前库]showtablesinmyhive;[创建表]creat
etableifnotexistsemployee(eidint,namestring,salarystring,
destinationstring)comment''employeedetails''--注释rowformatdelim
itedfieldsterminatedby''\t''--字段结束符linesterminatedby''\n''--行结
束符storedastextfile;--存储成何种文件[加载数据,覆盖原来数据]Linux:loaddatalocal
inpath''/soft/employee.txt''overwriteintotableemployee;Hdfs:
loaddatainpath''/soft/employee.txt''overwriteintotableemplo
yee;[加载数据,追加数据]Linux:loaddatalocalinpath''/soft/employee.txt''
intotableemployee;Hdfs:loaddatainpath''/soft/employee.txt''
intotableemployee;[导出数据,覆盖原有数据]Linux:insertoverwritelocaldi
rectory''/soft/data''selectfromhivedb.test1whereprovince=''h
ebei'';Hdfs:insertoverwritedirectory''/user/hadoop/data/out20''s
electfromhivedb.test1whereprovince=''hebei'';[导出数据到多个目录]from
hivedb.test1tinsertoverwritedirectory''/user/hadoop/data/out2
1/hebei''selectwheret.province=''hebei''insertoverwritedirec
tory''/user/hadoop/data/out21/henan''selectwheret.province=''h
enan'';Hive数据单元Databases:数据库。概念等同于关系型数据库的Schema,不多解释;Tables:表。概念等同
于关系型数据库的表,不多解释;Partitions:分区。概念类似于关系型数据库的表分区,没有那么多分区类型,只支持固定分区,将同
一组数据存放至一个固定的分区中。Buckets(orClusters):分桶。同一个分区内的数据还可以细分,将相同的KEY再划
分至一个桶中,这个有点类似于HASH分区,只不过这里是HASH分桶,也有点类似子分区吧。Hive数据类型基本类型类型size举例对应Java举例tinyint1byte20bytesmallint2byte20shortint4byte20intbigint8bytesignedinteger20longbooleanBooleantrueorfalsetruebooleanfloatSingleprecisionfloatingpoint3.14159floatdoubleDoubleprecisionfloatingpoint3.14159doublestring字符串‘hello’,”hello”“”timestampbinary字节数组集合类型STRUCTstruct(''jone'',''doae'');MAPmap(''fi'',''d'',''ddd'')ARRAYarray(''Jone'',''doe'')实例演练[Struct使用]createtablestudent_test(idint,infostruct)rowformatdelimitedfieldsterminatedby'',''collectionitemsterminatedby'':'';//''FIELDSTERMINATEDBY'',段与字段之间的分隔符//''''COLLECTIONITEMSTERMINATEDBY'':一个字段各个item的分隔符准备数据[root@namenodesoft]#catstudent_test.txt1,lilei:152,hanmeimei:263,lucy:18导入数据loaddatalocalinpath''/soft/student_test.txt''intotablestudent_test;查询selectinfo.namefromstudent_test;[Array使用]createtableclass_test(namestring,student_id_listarray)rowformatdelimitedfieldsterminatedby'',''collectionitemsterminatedby'':'';准备数据[root@namenodesoft]#catclass_test.txt78班,2:4:2379班,3:5:24:1480班,1:7:13:20导入数据loaddatalocalinpath''/soft/class_test.txt''intotableclass_test;查询selectname,student_id_list[1]fromclass_test;[Map使用]createtableemployee_test(idstring,perfmap)rowformatdelimitedfieldsterminatedby''\t''collectionitemsterminatedby'',''mapkeysterminatedby'':'';准备数据[root@namenodesoft]#catemployee_test.txt1name:12,age:232shouru:45,salay:3000导入数据loaddatalocalinpath''/soft/employee_test.txt''intotableemployee_test;查询selectperf[''name'']fromemployee_test;4A项目组魁魁语录:数据仓库、海量数据分析4A项目组江湖一哥版权所有
献花(0)
+1
(本文系王守奎的图...原创)