大数据学习第18天:

大数据学习第18天:

了解hive是什么**

背景

说到这个问题,还得先说个小故事,在很久很久以前…

有一个叫facebook的贼有名的公司,他们内部搭建了数据仓库(你可以理解成把一大堆数据放到一个地方,然后做报表给老板看!),是基于mysql的。后来随着数据量的不断增加,这种传统的数据库扛不住了…于是经过一系列的折腾换到了hadoop上(hadoop是个大数据体系,用的是里面的hdfs,做存储的。你可以理解成搞一堆破烂机器凑成个集群,然后存储超级多的数据)。

问题来了!

以前基于数据库的数据仓库用sql就能做查询,现在换到hdfs上面,得跑Mapreduce任务去做分析,这样以前做分析的人还得学mapreduce,好难呀!

于是…他们就开发了一套框架就是用sql来做hdfs的查询(用户输入的是sql,框架内部把sql转成mapreduce的任务,然后再去跑分析)。

解决的问题

Hive基于类似SQL的语言完成对hdfs数据的查询分析。

那么它到底做了什么呢?

img

  • 1 它支持各种命令,比如dfs的命令、脚本的执行
  • 2 如果你输入的是sql,它会交给一个叫做Driver的东东,去编译解析。
  • 3 把编译出来的东西交给hadoop去跑…然后返回查询结果。

说了这么多,其实你就可以把hive理解成搭建在hadoop(hdfs和mapreduce)之上的语言壳子…

理解hive架构

img

hive搭建

(1)从官网下载hive安装包,推荐使用Hive-1.2.1【因为Hive1.x底层是MapReduce,自Hive2.x后改为Spark】

(2)将Hive-1.2.1导入到服务器,进入/hive-1.2.1/conf文件夹中,里面有个hive-default.xml.template文件,里面是hive的默认配置信息。

(3)由于hive的metastore存储在MySQL中,那么hive所在的服务器怎么知道你连接哪个MySQL服务器呢?那么就需要手动配置一下MySQL相关信息,所以在hive-1.2.1/conf下创建一个hive-site.xml,用于配置数据库MySQL相关信息,该文件会覆盖hive-default.xml.template中的相关配置。

hive-site.xml:

<configuration>
  <property>
	<name>javax.jdo.option.ConnectionURL</name>
	<value>jdbc:mysql://hdp-03:3306/hive?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>root</value>
	<description>username to use against metastore database</description>
  </property>

  <property>
	<name>javax.jdo.option.ConnectionPassword</name>
	<value>root</value>
	<description>password to use against metastore database</description>
  </property>
</configuration>

(4)hive服务器默认不带mysql驱动包,所以将mysql-connector-java-5.1.39.jar 上传到hive-1.2.1/lib包下

(5)配置HADOOP_HOME和HIVE_HOME到环境变量中 : vi /etc/profile ------> source /etc/profile

(6)hive启动测试 直接输入hive即可出现 hive> (交互性界面)

设置一些基本参数,让hive使用起来更便捷,比如:

让提示符显示当前库:

hive>set hive.cli.print.current.db=true;

显示查询结果时显示字段名称:

hive>set hive.cli.print.header=true;

但是这样设置只对当前会话有效,重启hive会话后就失效,解决办法:

在linux的当前用户目录【root用户为/root下】中,编辑一个.hiverc文件,将参数写入其中:

vi .hiverc
set hive.cli.print.header=true;

set hive.cli.print.current.db=true;

脚本化运行【生产环境】

大量的hive查询任务,如果用交互式shell来进行输入的话,显然效率及其低下,因此,生产中更多的是使用脚本化运行机制:

该机制的核心点是:hive可以用一次性命令的方式来执行给定的hql语句

[root@hdp-02 ~]# hive -e “insert into table t_dest select * from t_src;”

然后,进一步,可以将上述命令写入shell脚本中,以便于脚本化运行hive任务,并控制、调度众多hive任务,示例如下:

书写shell脚本, vi t_order_etl.sh

#!/bin/bash
hive -e "select * from db_order.t_order"
hive -e "select * from default.t_user"
hql="create table  default.t_bash as select * from db_order.t_order"
hive -e "$hql"

直接执行sh文件即可如 ./ t_order_etl.sh

【常见做法】

如果要执行的hql语句特别复杂,那么,可以把hql语句写入一个文件: vi x.hql

select * from db_order.t_order;
select count(1) from db_order.t_user;

然后,用hive -f /root/x.hql 来执行

hive建库建表与数据导入

建库

hive中有一个默认的库:

库名:default

库目录:hdfs://hdp-02:9000/user/hive/warehouse


新建库:

create database db_order;

库建好后,在hdfs中会生成一个库目录:

hdfs://hdp-02:9000/user/hive/warehouse/db_order.db

建表

基本建表语句

use db_order;

create table t_order(id string,create_time string,amount float,uid string);

表建好后,会在所属的库目录中生成一个表目录

hdfs://hdp-02:9000/user/hive/warehouse/db_order.db/t_order

只是,这样建表的话,hive会认为表数据文件中的字段分隔符为^A (对应键盘control V + control A)

正确的建表语句为:

create table t_order(id string,create_time string,amount float,uid string)

row format delimited

fields terminated by ',';

这样就指定了,我们的表数据文件中的字段分隔符为","

删除表

drop table t_order;

删除表的效果是:

hive会从元数据库中清除关于这个表的信息;

hive还会从hdfs中删除这个表的表目录;


内部表与外部表

内部表(MANAGED_TABLE):表目录按照hive的规范来部署,位于hive的仓库目录/user/hive/warehouse中

外部表(EXTERNAL_TABLE):表目录由建表用户自己指定[如我们采集到的日志在/log/2019-04-09中],想实现该文件与hive的映射关系,则无需将日志文件移动到/user/hive/warehouse中,一是为了方便,二是担心因为移动文件而对外部程序造成影响。

create external table t_access(ip string,url string,access_time string)

row format delimited

fields terminated by ','

location '/log/2019-04-09';

外部表和内部表的特性差别:

内部表的目录在hive的仓库目录中 , 外部表的目录由用户指定
​ drop一个内部表时:hive会清除相关元数据,并删除表数据目录
​ drop一个外部表时:hive只会清除相关元数据;
一个hive的数据仓库,最底层的表,一定是来自于外部系统,为了不影响外部系统的工作逻辑,在hive中可建external表来映射这些外部系统产生的数据目录;然后,后续的ETL操作,产生的各种表建议用managed_table

7.2.4 分区表

分区表的实质是:在表目录中为数据文件创建分区子目录,以便于在查询时,MR程序可以针对分区子目录中的数据进行处理,缩减读取数据的范围。

比如,网站每天产生的浏览记录,浏览记录应该建一个表来存放,但是,有时候,我们可能只需要对某一天的浏览记录进行分析

这时,就可以将这个表建为分区表,每天的数据导入其中的一个分区

当然,每日的分区目录,应该有一个目录名(分区字段)

/user/hive/warehouse/t_pv_log/day=2019-04-08/
			    /day=2019-04-09/

/user/hive/warehouse/t_buyer_log/city=beijing/
			    /city=shanghai/

这样的话,day=2019-04-08和day=2019-04-09都属于t_pv_log,在查询的时候可以按日期查,也可以根据t_pv_log一起查出来,十分方便。

7.2.4.1 一个分区字段的实例:

1、创建带分区的表

create table t_access(ip string,url string,access_time string)

partitioned by(day string)

row format delimited

fields terminated by ',';

将来把数据向表中insert的时候,就需要指定一个day了,如day=2017-09-16,指定之后就插入到该目录。(plus:这个子目录day=2017-09-16并不是在建表时候就有的,而是在插入/导入数据时候才在HDFS中生成该目录的)

注意:分区字段不能是表定义中的已存在字段,否则会冲突,实际上分区字段是伪字段,在select查询时也会显示出来。

2、向分区中导入数据

load data local inpath '/root/access.log.2019-04-08.log' into table t_access partition(day='20190408');

load data local inpath '/root/access.log.2019-04-09.log' into table t_access partition(day='20190409');

【注意点:local inpath是指hive服务端所在的机器的本地目录】,导入后发现/user/hive/warehouse/access.db/t_access下生成了对应的文件夹day='20190408和day='20190409,而day='20190408文件内部是我们上传的log日志文件

3、针对分区数据进行查询

a、统计4月8号的总PV:

select count(*) from t_access where day='20190408';

实质:就是将分区字段当成表字段来用【实际上是伪字段】,就可以使用where子句指定分区了

b、统计表中所有数据总的PV:

select count(*) from t_access;

实质:不指定分区条件即可

7.3 数据导入导出

方式1:导入数据的一种方式:
手动用hdfs命令,将文件放入表目录;

方式2:在hive的交互式shell中用hive命令来导入本地数据到表目录

hive>load data local inpath ‘/root/order.data.2’ into table t_order;

方式3:用hive命令导入hdfs中的数据文件到表目录

hive>load data inpath ‘/access.log.2019-04-09.log’ into table t_access partition(dt=‘20190409’);

注意:导本地文件和导HDFS文件的区别:
本地文件导入表:复制
hdfs文件导入表:移动(实际上是移动到表所在文件夹内部)

将hive表中的数据导出到指定路径的文件

(1)将hive表中的数据导入HDFS的文件

insert overwrite directory '/root/access-data'

row format delimited fields terminated by ','

select * from t_access;

(2)将hive表中的数据导入本地磁盘文件

insert overwrite local directory '/root/access-data'

row format delimited fields terminated by ','

select * from t_access limit 100000;


7.4 hive文件格式

HIVE支持很多种文件格式:SEQUENCE FILE | TEXT FILE | PARQUET FILE | RC FILE

《Hive文件格式之textfile,sequencefile和rcfile的使用与区别详解》

create table t_pq(movie string,rate int) stored as textfile;

create table t_pq(movie string,rate int) stored as sequencefile;

create table t_pq(movie string,rate int) stored as parquetfile;

演示:
1、先建一个存储文本文件的表

create table t_access_text(ip string, url string,access_time string)
row format delimited fields terminated by ','
stored as textfile

;

导入文本数据到表中:

load data local inpath ‘/root/access-data/000000_0’ into table t_access_text;

2、建一个存储sequence file文件的表:

create table t_access_seq(ip string,url string,access_time string)
stored as sequencefile;

从文本表中查询数据插入sequencefile表中,生成数据文件就是sequencefile格式的了:

insert into t_access_seq
select * from t_access_text;

3、建一个存储parquet file文件的表:

create table t_access_parq(ip string,url string,access_time string)

Hive数据类型

数字类型
TINYINT                    (1-byte signed integer, from -128 to 127)

SMALLINT                (2-byte signed integer, from -32,768 to 32,767)

INT/INTEGER            (4-byte signed integer, from -2,147,483,648 to 2,147,483,647)

BIGINT                      (8-byte signed integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)

FLOAT                       (4-byte single  precision floating point number)

DOUBLE                   (8-byte double precision floating point number)

示例:

create table t_test(a string ,b int,c bigint,d float,e double,f tinyint,g smallint)

8.2 日期时间类型

TIMESTAMP (Note: Only available starting with Hive 0.8.0)
DATE (Note: Only available starting with Hive 0.12.0)

示例,假如有以下数据文件:

1,zhangsan,1985-06-30
2,lisi,1986-07-10
3,wangwu,1985-08-09

那么,就可以建一个表来对数据进行映射

create table t_customer(id int,name string,birthday date)

row format delimited fields terminated by ‘,’;

然后导入数据

load data local inpath ‘/root/customer.dat’ into table t_customer;

然后,就可以正确查询

8.3 字符串类型

STRING

VARCHAR           (Note: Only available starting with Hive 0.12.0)

CHAR                  (Note: Only available starting with Hive 0.13.0)




8.4 混杂类型

BOOLEAN
BINARY (Note: Only available starting with Hive 0.8.0)

8.5 复合类型

8.5.1 array数组类型

arrays: ARRAY<data_type> (Note: negative values and non-constant expressions are allowed as of Hive 0.14)

示例:array类型的应用

假如有如下数据需要用hive的表去映射:

设想:如果主演信息用一个数组来映射比较方便

建表:

create table t_movie(moive_name string , actors array<string> , first_show date)

row format delimited 

fields terminated by ','

collection items terminated by ':';

导入数据:

load data local inpath ‘/root/movie.dat’ into table t_movie;

查询:

select * from t_movie;

select moive_name,actors[0] from t_movie;

– 使用array_containns(field,‘keyword’)看某字段是否包含keyword
select moive_name,actors from t_movie where array_contains(actors,‘吴刚’);

– 求每部电影中包含多少位主演(actors是array类型, size(field) 数组的长度函数)
select moive_name,size(actors) from t_movie;

8.5.2 map类型

maps: MAP<primitive_type, data_type> (Note: negative values and non-constant expressions are allowed as of Hive 0.14.)

1、假如有以下数据:

1,zhangsan,father:xiaoming#mother:xiaohuang#brother:xiaoxu,28
2,lisi,father:mayun#mother:huangyi#brother:guanyu,22
3,wangwu,father:xiaolin#mother:ruhua#sister:xiaoniu,29
4,mayun,father:mababa#mother:xiaoqiang,26

可以用一个map类型来对上述数据中key-value的家庭成员进行描述

2、建表语句:

create table t_person(id int,name string,family_members map<string,string>,age int)

row format delimited fields terminated by ‘,’

collection items terminated by ‘#’

map keys terminated by ‘:’;

3、查询

select * from t_person;

取map字段的指定key的值(查出每个人的爸爸)

select id,name,family_members[‘father’] as father from t_person;

取map字段的所有key(查出每个人的亲属关系)

select id,name,map_keys(family_members) as relation from t_person;

取map字段的所有value(查出每个人亲人的名字)

select id,name,map_values(family_members) from t_person;

##查出每个人中亲人的数量(使用size() 函数)

select id,name,size(family_members) as relations,age from t_person;

综合:查询有brother的用户信息[谁有兄弟、兄弟是谁]

– 方式1
select id,name,father
from
(select id,name,family_members[‘brother’] as brother_name from t_person) tmp
where brother_name is not null;

–方式2
select id,name,age, famaily_members[‘brother’]
from t_person where array_contains(map_key(famaily_members),‘brother’);

struct类型

structs: STRUCT<col_name : data_type, …>

1、假如有如下数据:

1,zhangsan,18:male:beijing
2,lisi,28:female:shanghai

其中的用户信息包含:年龄:整数,性别:字符串,地址:字符串

设想用一个字段来描述整个用户信息,可以采用struct

2、建表:

create table t_person_struct(id int,name string,info struct<age:int,sex:string,addr:string>)

row format delimited fields terminated by ','

collection items terminated by ':';

3、查询

select * from t_person_struct;

– 查询 id , name , 年龄
select id,name,info.age from t_person_struct;

分区

Hive 分区partition

必须在表定义时指定对应的partition字段

a、单分区建表语句:

create table day_table (id int, content string) partitioned by (dt string);

单分区表,按天分区,在表结构中存在id,content,dt三列。

以dt为文件夹区分

b、 双分区建表语句:

create table day_hour_table (id int, content string) partitioned by (dt string, hour string);

双分区表,按天和小时分区,在表结构中新增加了dt和hour两列。

先以dt为文件夹,再以hour子文件夹区分

Hive添加分区表语法

(表已创建,在此基础上添加分区):

ALTER TABLE table_name ADD [IF NOT EXISTS] PARTITION partition_spec [LOCATION ‘location1’] partition_spec [LOCATION ‘location2’] …;

partition_spec:
(partition_column = partition_col_value, partition_column = partition_col_value, …)

例:

ALTER TABLE day_table ADD PARTITION (dt=‘2008-08-08’, hour=‘08’)

Hive删除分区语法:

ALTER TABLE table_name DROP partition_spec, partition_spec,…

partition_spec:
(partition_column = partition_col_value, partition_column = partition_col_value, …)

用户可以用 ALTER TABLE DROP PARTITION 来删除分区。

内部表中、对应分区的元数据和数据将被一并删除。

例:

ALTER TABLE day_hour_table DROP PARTITION (dt=‘2008-08-08’, hour=‘09’);

Hive向指定分区添加数据语法:

LOAD DATA [LOCAL] INPATH ‘filepath’ [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 …)]

例:

LOAD DATA INPATH ‘/user/pv.txt’ INTO TABLE day_hour_table PARTITION(dt=‘2008-08- 08’, hour=‘08’);

LOAD DATA local INPATH ‘/user/hua/*’ INTO TABLE day_hour partition(dt=‘2010-07- 07’);

当数据被加载至表中时,不会对数据进行任何转换。Load操作只是将数据复制至Hive表对应的位置。数据加载时在表下自动创建一个目录

Hive查询执行分区语法

SELECT day_table.* FROM day_table WHERE day_table.dt>= ‘2008-08-08’;

分区表的意义在于优化查询。查询时尽量利用分区字段。如果不使用分区字段,就会全部扫描。

Hive查询表的分区信息语法:

SHOW PARTITIONS day_hour_table;

预先导入分区数据,但是无法识别怎么办

Msck repair table tablename

直接添加分区

beeline和JDBC

Beeline 是一个 Hive 客户端,包含在 HDInsight 群集的头节点上。Beeline is a Hive client that is included on the head nodes of your HDInsight cluster. Beeline 使用 JDBC 连接到 HiveServer2,后者是 HDInsight 群集上托管的一项服务。Beeline uses JDBC to connect to HiveServer2, a service hosted on your HDInsight cluster. 还可以使用 Beeline 通过 Internet 远程访问 Hive on HDInsight。You can also use Beeline to access Hive on HDInsight remotely over the internet. 以下示例提供最常见的连接字符串,用于从 Beeline 连接到 HDInsight:The following examples provide the most common connection strings used to connect to HDInsight from Beeline:

  • 通过与头节点或边缘节点的 SSH 连接使用 BeelineUsing Beeline from an SSH connection to a headnode or edge node: -u 'jdbc:hive2://headnodehost:10001/;transportMode=http'
  • 在通过 Azure 虚拟网络连接到 HDInsight 的客户端上使用 BeelineUsing Beeline on a client, connecting to HDInsight over an Azure Virtual Network: -u 'jdbc:hive2://<headnode-FQDN>:10001/;transportMode=http'
  • 在通过公共 Internet 连接到 HDInsight 的客户端上使用 BeelineUsing Beeline on a client, connecting to HDInsight over the public internet: -u 'jdbc:hive2://clustername.azurehdinsight.cn:443/;ssl=true;transportMode=http;httpPath=/hive2' -n admin -p password

备注

admin 替换为群集的群集登录帐户。Replace admin with the cluster login account for your cluster.

password 替换为群集登录帐户的密码。Replace password with the password for the cluster login account.

clustername 替换为 HDInsight 群集的名称。Replace clustername with the name of your HDInsight cluster.

通过虚拟网络连接到群集时,将 <headnode-FQDN> 替换为群集头节点的完全限定域名。When connecting to the cluster through a virtual network, replace <headnode-FQDN> with the fully qualified domain name of a cluster headnode.

先决条件Prerequisites

  • 基于 Linux 的 Hadoop on HDInsight 群集版本 3.4 或更高版本。A Linux-based Hadoop on HDInsight cluster version 3.4 or greater.

    重要

    Linux 是 HDInsight 3.4 或更高版本上使用的唯一操作系统。Linux is the only operating system used on HDInsight version 3.4 or greater. 有关详细信息,请参阅 HDInsight 在 Windows 上停用。For more information, see HDInsight retirement on Windows.

  • SSH 客户端或本地 Beeline 客户端。An SSH client or a local Beeline client. 本文档中的大多数步骤都假定从与群集的 SSH 会话使用 Beeline。Most of the steps in this document assume that you are using Beeline from an SSH session to the cluster. 有关从群集外部运行 Beeline 的信息,请参阅远程使用 Beeline 部分。For information on running Beeline from outside the cluster, see the use Beeline remotely section.

    有关使用 SSH 的详细信息,请参阅将 SSH 与 HDInsight 配合使用。For more information on using SSH, see Use SSH with HDInsight.

运行 Hive 查询Run a Hive query

  1. 启动 Beeline 时,必须提供用于 HDInsight 群集上的 HiveServer2 的连接字符串:When starting Beeline, you must provide a connection string for HiveServer2 on your HDInsight cluster:

    • 通过公共 Internet 连接时,必须提供群集登录帐户名(默认 admin)和密码。When connecting over the public internet, you must provide the cluster login account name (default admin) and password. 例如,使用 Beeline 从客户端系统连接到 <clustername>.azurehdinsight.cn 地址。For example, using Beeline from a client system to connect to the <clustername>.azurehdinsight.cn address. 此连接通过端口 443 建立,并使用 SSL 进行加密:This connection is made over port 443, and is encrypted using SSL:

      bash复制

      beeline -u 'jdbc:hive2://clustername.azurehdinsight.cn:443/;ssl=true;transportMode=http;httpPath=/hive2' -n admin -p password
      
    • 从 SSH 会话连接到群集头节点时,可以连接到端口 headnodehost 上的 10001 地址:When connecting from an SSH session to a cluster headnode, you can connect to the headnodehost address on port 10001:

      bash复制

      beeline -u 'jdbc:hive2://headnodehost:10001/;transportMode=http'
      
    • 通过 Azure 虚拟网络连接时,必须提供群集头节点的完全限定域名 (FQDN)。When connecting over an Azure Virtual Network, you must provide the fully qualified domain name (FQDN) of a cluster head node. 由于直接与群集节点建立此连接,因此此连接使用端口 10001:Since this connection is made directly to the cluster nodes, the connection uses port 10001:

      bash复制

      beeline -u 'jdbc:hive2://<headnode-FQDN>:10001/;transportMode=http'
      
  2. Beeline 命令以 ! 字符开头,例如,!help 显示帮助。Beeline commands begin with a ! character, for example !help displays help. 但是,! 对于某些命令可以省略。However the ! can be omitted for some commands. 例如,help 也是有效的。For example, help also works.

    有一个 !sql,用于执行 HiveQL 语句。There is a !sql, which is used to execute HiveQL statements. 但是,由于 HiveQL 非常流行,因此可以省略前面的 !sql。However, HiveQL is so commonly used that you can omit the preceding !sql. 以下两个语句等效:The following two statements are equivalent:

    hiveql复制

    !sql show tables;
    show tables;
    

    在新群集上,只会列出一个表:hivesampletable。On a new cluster, only one table is listed: hivesampletable.

  3. 使用以下命令显示 hivesampletable 的架构:Use the following command to display the schema for the hivesampletable:

    hiveql复制

    describe hivesampletable;
    

    此命令返回以下信息:This command returns the following information:

    复制

     +-----------------------+------------+----------+--+
     |       col_name        | data_type  | comment  |
     +-----------------------+------------+----------+--+
     | clientid              | string     |          |
     | querytime             | string     |          |
     | market                | string     |          |
     | deviceplatform        | string     |          |
     | devicemake            | string     |          |
     | devicemodel           | string     |          |
     | state                 | string     |          |
     | country               | string     |          |
     | querydwelltime        | double     |          |
     | sessionid             | bigint     |          |
     | sessionpagevieworder  | bigint     |          |
     +-----------------------+------------+----------+--+
    

    此信息描述表中的列。This information describes the columns in the table.

  4. 输入以下语句,以使用 HDInsight 群集随附的示例数据来创建名为 log4jLogs 的表:Enter the following statements to create a table named log4jLogs by using sample data provided with the HDInsight cluster:

    hiveql复制

    DROP TABLE log4jLogs;
    CREATE EXTERNAL TABLE log4jLogs (
        t1 string,
        t2 string,
        t3 string,
        t4 string,
        t5 string,
        t6 string,
        t7 string)
    ROW FORMAT DELIMITED FIELDS TERMINATED BY ' '
    STORED AS TEXTFILE LOCATION 'wasb:///example/data/';
    SELECT t4 AS sev, COUNT(*) AS count FROM log4jLogs 
        WHERE t4 = '[ERROR]' AND INPUT__FILE__NAME LIKE '%.log' 
        GROUP BY t4;
    

    这些语句执行以下操作:These statements perform the following actions:

    • DROP TABLE - 如果表存在,则将其删除。- If the table exists, it is deleted.
    • CREATE EXTERNAL TABLE - 在 Hive 中创建一个外部表。- Creates an external table in Hive. 外部表只会在 Hive 中存储表定义。External tables only store the table definition in Hive. 数据保留在原始位置。The data is left in the original location.
    • ROW FORMAT - 如何设置数据的格式。- How the data is formatted. 在此情况下,每个日志中的字段以空格分隔。In this case, the fields in each log are separated by a space.
    • STORED AS TEXTFILE LOCATION - 数据存储位置和文件格式。- Where the data is stored and in what file format.
    • SELECT - 选择 t4 列包含值 [ERROR] 的所有行的计数。- Selects a count of all rows where column t4 contains the value [ERROR]. 此查询返回值 3,因为有三行包含此值。This query returns a value of 3 as there are three rows that contain this value.
    • INPUT__FILE__NAME LIKE '%.log' - Hive 会尝试向目录中的所有文件应用架构。- Hive attempts to apply the schema to all files in the directory. 在此示例中,目录包含与架构不匹配的文件。In this case, the directory contains files that do not match the schema. 为防止结果中包含垃圾数据,此语句指示 Hive 应当仅返回以 .log 结尾的文件中的数据。To prevent garbage data in the results, this statement tells Hive that it should only return data from files ending in .log.

    备注

    如果希望通过外部源更新基础数据,应使用外部表。External tables should be used when you expect the underlying data to be updated by an external source. 例如,自动化数据上传进程或 MapReduce 操作。For example, an automated data upload process or a MapReduce operation.

    删除外部表不会删除数据,只会删除表定义。Dropping an external table does not delete the data, only the table definition.

    此命令的输出类似于以下文本:The output of this command is similar to the following text:

    复制

    INFO  : Tez session hasn't been created yet. Opening session
    INFO  :
    
    INFO  : Status: Running (Executing on YARN cluster with App id application_1443698635933_0001)
    
    INFO  : Map 1: -/-      Reducer 2: 0/1
    INFO  : Map 1: 0/1      Reducer 2: 0/1
    INFO  : Map 1: 0/1      Reducer 2: 0/1
    INFO  : Map 1: 0/1      Reducer 2: 0/1
    INFO  : Map 1: 0/1      Reducer 2: 0/1
    INFO  : Map 1: 0(+1)/1  Reducer 2: 0/1
    INFO  : Map 1: 0(+1)/1  Reducer 2: 0/1
    INFO  : Map 1: 1/1      Reducer 2: 0/1
    INFO  : Map 1: 1/1      Reducer 2: 0(+1)/1
    INFO  : Map 1: 1/1      Reducer 2: 1/1
    +----------+--------+--+
    |   sev    | count  |
    +----------+--------+--+
    | [ERROR]  | 3      |
    +----------+--------+--+
    1 row selected (47.351 seconds)
    
  5. 若要退出 Beeline,请使用 !exit。To exit Beeline, use !exit.

使用 Beeline 运行 HiveQL 文件Use Beeline to run a HiveQL file

使用以下步骤创建文件,并使用 Beeline 运行该文件。Use the following steps to create a file, then run it using Beeline.

  1. 使用以下命令创建一个名为 query.hql 的文件:Use the following command to create a file named query.hql:

    bash复制

    nano query.hql
    
  2. 将以下文本用作文件的内容。Use the following text as the contents of the file. 此查询创建名为 errorLogs 的新“内部”表:This query creates a new ‘internal’ table named errorLogs:

    hiveql复制

    CREATE TABLE IF NOT EXISTS errorLogs (t1 string, t2 string, t3 string, t4 string, t5 string, t6 string, t7 string) STORED AS ORC;
    INSERT OVERWRITE TABLE errorLogs SELECT t1, t2, t3, t4, t5, t6, t7 FROM log4jLogs WHERE t4 = '[ERROR]' AND INPUT__FILE__NAME LIKE '%.log';
    

    这些语句执行以下操作:These statements perform the following actions:

    • CREATE TABLE IF NOT EXISTS - 创建表(如果该表尚不存在)。CREATE TABLE IF NOT EXISTS - If the table does not already exist, it is created. 因为未使用 EXTERNAL 关键字,此语句创建内部表。Since the EXTERNAL keyword is not used, this statement creates an internal table. 内部表存储在 Hive 数据仓库中,由 Hive 全权管理。Internal tables are stored in the Hive data warehouse and are managed completely by Hive.

    • STORED AS ORC:以优化行纵栏表 (ORC) 格式存储数据。STORED AS ORC - Stores the data in Optimized Row Columnar (ORC) format. ORC 格式是高度优化且有效的 Hive 数据存储格式。ORC format is a highly optimized and efficient format for storing Hive data.

    • INSERT OVERWRITE …SELECT- 从包含 [ERROR]log4jLogs 表中选择行,然后将数据插入 errorLogs 表中。INSERT OVERWRITE … SELECT - Selects rows from the log4jLogs table that contain [ERROR], then inserts the data into the errorLogs table.

      备注

      与外部表不同,删除内部表会同时删除基础数据。Unlike external tables, dropping an internal table deletes the underlying data as well.

  3. 如果要保存文件,请使用 Ctrl+_X,并输入 Y,最后按 Enter。To save the file, use Ctrl+_X, then enter Y, and finally Enter.

  4. 使用以下命令通过 Beeline 运行该文件:Use the following to run the file using Beeline:

    bash复制

    beeline -u 'jdbc:hive2://headnodehost:10001/;transportMode=http' -i query.hql
    

    备注

    -i 参数启动 Beeline,并运行 query.hql 文件中的语句。The -i parameter starts Beeline and runs the statements in the query.hql file. 查询完成后,会出现 jdbc:hive2://headnodehost:10001/> 提示符。Once the query completes, you arrive at the jdbc:hive2://headnodehost:10001/> prompt. 还可以使用 -f 参数运行文件,该参数在查询完成后会退出 Beeline。You can also run a file using the -f parameter, which exits Beeline after the query completes.

  5. 若要验证是否已创建 errorLogs 表,请使用以下语句从 errorLogs 返回所有行:To verify that the errorLogs table was created, use the following statement to return all the rows from errorLogs:

    hiveql复制

    SELECT * from errorLogs;
    

    应返回三行数据,所有行都包含 t4 列中的 [ERROR]:Three rows of data should be returned, all containing [ERROR] in column t4:

    复制

     +---------------+---------------+---------------+---------------+---------------+---------------+---------------+--+
     | errorlogs.t1  | errorlogs.t2  | errorlogs.t3  | errorlogs.t4  | errorlogs.t5  | errorlogs.t6  | errorlogs.t7  |
     +---------------+---------------+---------------+---------------+---------------+---------------+---------------+--+
     | 2012-02-03    | 18:35:34      | SampleClass0  | [ERROR]       | incorrect     | id            |               |
     | 2012-02-03    | 18:55:54      | SampleClass1  | [ERROR]       | incorrect     | id            |               |
     | 2012-02-03    | 19:25:27      | SampleClass4  | [ERROR]       | incorrect     | id            |               |
     +---------------+---------------+---------------+---------------+---------------+---------------+---------------+--+
     3 rows selected (1.538 seconds)
    

远程使用 BeelineUse Beeline remotely

如果本地安装了 Beeline 并通过公共 Internet 进行连接,请使用以下参数:If you have Beeline installed locally, and connect over the public internet, use the following parameters:

  • 连接字符串Connection string: -u 'jdbc:hive2://clustername.azurehdinsight.cn:443/;ssl=true;transportMode=http;httpPath=/hive2'
  • 群集登录名Cluster login name: -n admin
  • 群集登录密码Cluster login password -p 'password'

将连接字符串中的 clustername 替换为 HDInsight 群集名称。Replace the clustername in the connection string with the name of your HDInsight cluster.

admin 替换为群集登录名称,并将 password 替换为群集登录密码。Replace admin with the name of your cluster login, and replace password with the password for your cluster login.

如果本地安装了 Beeline 并通过 Azure 虚拟网络进行连接,请使用以下参数:If you have Beeline installed locally, and connect over an Azure Virtual Network, use the following parameters:

  • 连接字符串Connection string: -u 'jdbc:hive2://<headnode-FQDN>:10001/;transportMode=http'

若要查找头节点的完全限定域名,请使用使用 Apache Ambari REST API 管理 HDInsight 文档中的信息。To find the fully qualified domain name of a headnode, use the information in the Manage HDInsight using the Apache Ambari REST API document.

将 Beeline 与 Apache Spark 配合使用Use Beeline with Apache Spark

Apache Spark 提供自己的 HiveServer2 实现(有时称为 Spark Thrift 服务器)。Apache Spark provides its own implementation of HiveServer2, which is sometimes referred to as the Spark Thrift server. 此服务使用 Spark SQL 而不是 Hive 来解析查询,并且可以根据查询改善性能。This service uses Spark SQL to resolve queries instead of Hive, and may provide better performance depending on your query.

通过 Internet 进行连接时使用的__连接字符串__略有不同。The connection string used when connecting over the internet is slightly different. 它是 httpPath/sparkhive2 而不包含 httpPath=/hive2。Instead of containing httpPath=/hive2 it is httpPath/sparkhive2. 下面是通过 Internet 进行连接的示例:The following is an example of connecting over the internet:

bash复制

beeline -u 'jdbc:hive2://clustername.azurehdinsight.cn:443/;ssl=true;transportMode=http;httpPath=/sparkhive2' -n admin -p password

当直接从群集头节点或者从 HDInsight 群集所在的 Azure 虚拟网络中的资源进行连接时,应当为 Spark Thrift 服务器使用端口 10002 而非 10001。When connecting directly from the cluster head node, or from a resource inside the same Azure Virtual Network as the HDInsight cluster, port 10002 should be used for Spark Thrift server instead of 10001. 下面是直接连接到头节点的示例:The following is an example of connecting to directly to the head node:

bash复制

beeline -u 'jdbc:hive2://headnodehost:10002/;transportMode=http'

hive函数

Hive复合数据类型

1561641895696

Hive操作复合类型

Hive 内置函数

Date Functions

Conditional Functions

Misc. Functions

Hive 自定义函数

Hive的UDF开发只需要重构UDF类的evaluate函数即可。例:

package com.hrj.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;

public class helloUDF extends UDF {

​ public String evaluate(String str) {

​ try {

​ return "HelloWorld " + str;

​ } catch (Exception e) {

​ return null;

​ }

​ }

}

•Hive 自定义函数调用

将该java文件编译成helloudf.jar

hive> add jar helloudf.jar;

hive> create temporary function helloworld as ‘com.hrj.hive.udf.helloUDF’;

hive> select helloworld(t.col1) from t limit 10;

hive> drop temporary function helloworld;

•注意

1.helloworld为临时的函数,所以每次进入hive都需要add jar以及create temporary操作

2.UDF只能实现一进一出的操作,如果需要实现多进一出,则需要实现UDAF

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值