二、HIVE 基本操作



2.1 create table

总述

  • CREATE TABLE 创建一个指定名字的表。如果相同名字的表已经存在,则抛出异常;用户可以用 IF NOT EXIST 选项来忽略这个异常。
  • EXTERNAL 关键字可以让用户创建一个外部表,在建表的同时指定一个指向实际数据的路径(LOCATION)。
  • LIKE 允许用户复制现有的表结构,但是不复制数据。
  • 用户在建表的时候可以自定义 SerDe 或者使用自带的 SerDe。如果没有指定 ROW FORMAT 或者 ROW FORMAT DELIMITED,将会使用自带的 SerDe。在建表的时候,用户还需要为表指定列,用户在指定表的列的同时也会指定自定义的 SerDe,Hive 通过 SerDe 确定表的具体的列的数据。
  • 如果文件数据是纯文本,可以使用 STORED AS TEXTFILE。如果数据需要压缩,使用 STORED AS SEQUENCE。
  • 有分区的表可以在创建的时候使用 PARTITIONED BY 语句。一个表可以拥有一个或者多个分区,每一个分区单独存在一个目录下。而且,表和分区都可以对某个列进行 CLUSTERED BY 操作,将若干个列放入一个桶(bucket)中。也可以利用SORT BY 对数据进行排序。这样可以为特定应用提高性能。
  • 表名和列名不区分大小写,SerDe 和属性名区分大小写。表和列的注释是字符串。

语法

CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
  [(col_name data_type [COMMENT col_comment], ...)]
  [COMMENT table_comment]
  [PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)]
  [CLUSTERED BY (col_name, col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
  [
   [ROW FORMAT row_format] [STORED AS file_format]
   | STORED BY 'storage.handler.class.name' [ WITH SERDEPROPERTIES (...) ]  (Note:  only available starting with 0.6.0)
  ]
  [LOCATION hdfs_path]
  [TBLPROPERTIES (property_name=property_value, ...)]  (Note:  only available starting with 0.6.0)
  [AS select_statement]  (Note: this feature is only available starting with 0.5.0.)
 
 
CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
  LIKE existing_table_name
  [LOCATION hdfs_path]
 
data_type
  : primitive_type
  | array_type
  | map_type
  | struct_type
 
primitive_type
  : TINYINT
  | SMALLINT
  | INT
  | BIGINT
  | BOOLEAN
  | FLOAT
  | DOUBLE
  | STRING
 
array_type
  : ARRAY < data_type >
 
map_type
  : MAP < primitive_type, data_type >
 
struct_type
  : STRUCT < col_name : data_type [COMMENT col_comment], ...>
 
row_format
  : DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]
        [MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char]
  | SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]
 
file_format:
  : SEQUENCEFILE
  | TEXTFILE
  | RCFILE     (Note:  only available starting with 0.6.0)
  | INPUTFORMAT input_format_classname OUTPUTFORMAT output_format_classname
CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
  [(col_name data_type [COMMENT col_comment], ...)]
  [COMMENT table_comment]
  [PARTITIONED BY (col_name data_type [COMMENT col_comment], ...)]
  [CLUSTERED BY (col_name, col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
  [
   [ROW FORMAT row_format] [STORED AS file_format]
   | STORED BY 'storage.handler.class.name' [ WITH SERDEPROPERTIES (...) ]  (Note:  only available starting with 0.6.0)
  ]
  [LOCATION hdfs_path]
  [TBLPROPERTIES (property_name=property_value, ...)]  (Note:  only available starting with 0.6.0)
  [AS select_statement]  (Note: this feature is only available starting with 0.5.0.)
 
 
CREATE [EXTERNAL] TABLE [IF NOT EXISTS] table_name
  LIKE existing_table_name
  [LOCATION hdfs_path]
 
data_type
  : primitive_type
  | array_type
  | map_type
  | struct_type
 
primitive_type
  : TINYINT
  | SMALLINT
  | INT
  | BIGINT
  | BOOLEAN
  | FLOAT
  | DOUBLE
  | STRING
 
array_type
  : ARRAY < data_type >
 
map_type
  : MAP < primitive_type, data_type >
 
struct_type
  : STRUCT < col_name : data_type [COMMENT col_comment], ...>
 
row_format
  : DELIMITED [FIELDS TERMINATED BY char] [COLLECTION ITEMS TERMINATED BY char]
        [MAP KEYS TERMINATED BY char] [LINES TERMINATED BY char]
  | SERDE serde_name [WITH SERDEPROPERTIES (property_name=property_value, property_name=property_value, ...)]
 
file_format:
  : SEQUENCEFILE
  | TEXTFILE
  | RCFILE     (Note:  only available starting with 0.6.0)
  | INPUTFORMAT input_format_classname OUTPUTFORMAT output_format_classname

    目前在hive中常用的数据类型有:

BIGINT – 主要用于状态,类别,数量的字段, 如status/option/type/quantity

         DOUBLE – 主要用于金额的字段, 如fee/price/bid

         STRING – 除上述之外的字段基本都使用String, 尤其是id和日期时间这样的字段

基本例子

1、如果一个表已经存在,可以使用

if not exists
if not exists

2、

create table xiaojun(id int,cont string)   
    row format delimited fields      
    terminated by '\005'     
    stored as textfile;
create table xiaojun(id int,cont string)   
    row format delimited fields      
    terminated by '\005'     
    stored as textfile;


terminated by:关于来源的文本数据的字段间隔符

    如果要将自定义间隔符的文件读入一个表,需要通过创建表的语句来指明输入文件间隔符,然后load     data到这个表。

3、Alibaba数据库常用间隔符的读取

在hive中Ascii码5用’\005’表示, Ascii码7用’\007’表示,依此类推。

4、装载数据

    查看一下:Hadoop fs -ls

LOAD DATA INPATH '/user/admin/xiaojun/a.txt' OVERWRITE INTO TABLE xiaojun;
LOAD DATA INPATH '/user/admin/xiaojun/a.txt' OVERWRITE INTO TABLE xiaojun;


5、如果使用external建表和普通建表区别

A、指定一个位置,而不使用默认的位置。如:

create  EXTERNAL  table xiaojun(id int,cont string)  
    row format delimited fields  
    terminated by '\005'  
    stored as textfile  
    location '/user/admin/xiaojun/';
create  EXTERNAL  table xiaojun(id int,cont string)  
    row format delimited fields  
    terminated by '\005'  
    stored as textfile  
    location '/user/admin/xiaojun/';


--------------check结果

ij> select LOCATION from tbls a,sds b where a.sd_id=b.sd_id and tbl_name='xiaojun';

LOCATION                                                                               

----------------------------------------------------------------------------------------------

hdfs://hadoop1:7000/user/admin/xiaojun  

 

ij> select LOCATION from tbls a,sds b where a.sd_id=b.sd_id and tbl_name='c';

LOCATION                                                                                          -------------------------------------------------------------------------------------------------

hdfs://hadoop1:7000/user/hive/warehouse/c


B、对于使用create table external建表完成后,再drop掉表,表中的数据还在文件系统中。

如:

hive> create  EXTERNAL  table xiaojun(id int,cont string) row format delimited fields terminated by '\005' stored as textfile;

OK

hive> LOAD DATA INPATH '/user/admin/xiaojun' OVERWRITE INTO TABLE xiaojun;

Loading data to table xiaojun

OK

hive> drop table xiaojun;

OK

[admin@hadoop1 bin]$ ./hadoop fs -ls hdfs://hadoop1:7000/user/hive/warehouse/xiaojun


Found 1 items

使用普通的建表DROP后则找不到

创建分区例子

HIVE的分区通过在创建表时启用partition by实现,用来partition的维度并不是实际数据的某一列,具体分区的标志是由插入内容时给定的。当要查询某一分区的内容时可以采用where语句,形似where tablename.partition_key > a来实现。

创建含分区的表。

命令原型:

CREATE TABLE page_view(viewTime     INT,  
                       userid       BIGINT,
                       page_url     STRING,  
                       referrer_url STRING,
                       ip           STRING COMMENT 'IP Address of the User')
 COMMENT 'This is the page view table'
 PARTITIONED BY(dt STRING, country STRING)
 CLUSTERED BY(userid)  
 SORTED BY(viewTime) INTO 32 BUCKETS
 ROW FORMAT DELIMITED
 FIELDS TERMINATED BY '\001'
 COLLECTION ITEMS TERMINATED BY '\002'
 MAP KEYS TERMINATED BY '\003'
 STORED AS SEQUENCEFILE;
CREATE TABLE page_view(viewTime     INT,  
                       userid       BIGINT,
                       page_url     STRING,  
                       referrer_url STRING,
                       ip           STRING COMMENT 'IP Address of the User')
 COMMENT 'This is the page view table'
 PARTITIONED BY(dt STRING, country STRING)
 CLUSTERED BY(userid)  
 SORTED BY(viewTime) INTO 32 BUCKETS
 ROW FORMAT DELIMITED
 FIELDS TERMINATED BY '\001'
 COLLECTION ITEMS TERMINATED BY '\002'
 MAP KEYS TERMINATED BY '\003'
 STORED AS SEQUENCEFILE;

Eg:

建表:

CREATE TABLE c02_clickstat_fatdt1
(yyyymmdd  string,
 id               INT,
 ip               string,
 country          string,
 cookie_id        string,
 page_id          string  ,  
 clickstat_url_id int,
 query_string     string,
 refer            string
)PARTITIONED BY(dt STRING)
row format delimited  
fields terminated by '\005'  
stored as textfile;
CREATE TABLE c02_clickstat_fatdt1
(yyyymmdd  string,
 id               INT,
 ip               string,
 country          string,
 cookie_id        string,
 page_id          string  ,  
 clickstat_url_id int,
 query_string     string,
 refer            string
)PARTITIONED BY(dt STRING)
row format delimited  
fields terminated by '\005'  
stored as textfile;

装载数据:

LOAD DATA INPATH '/user/admin/SqlldrDat/CnClickstat/20101101/19/clickstat_gp_fatdt0/0' OVERWRITE INTO TABLE c02_clickstat_fatdt1 PARTITION(dt='20101101');
 
访问某一个分区
SELECT count(*) FROM c02_clickstat_fatdt1 a
    WHERE a.dt >= '20101101' AND a.dt < '20101102';
LOAD DATA INPATH '/user/admin/SqlldrDat/CnClickstat/20101101/19/clickstat_gp_fatdt0/0' OVERWRITE INTO TABLE c02_clickstat_fatdt1 PARTITION(dt='20101101');
 
访问某一个分区
SELECT count(*) FROM c02_clickstat_fatdt1 a
    WHERE a.dt >= '20101101' AND a.dt < '20101102';

其它例子

指定LOCATION位置:

CREATE EXTERNAL TABLE page_view(viewTime       INT,  
                                userid         BIGINT,
                                page_url       STRING,  
                                referrer_url   STRING,
                                ip             STRING COMMENT 'IP Address of the User',
                                country        STRING COMMENT 'country of origination')
 COMMENT 'This is the staging page view table'
 ROW FORMAT DELIMITED  
 FIELDS TERMINATED BY '\054'
 STORED AS TEXTFILE
 LOCATION '<hdfs_location>'
CREATE EXTERNAL TABLE page_view(viewTime       INT,  
                                userid         BIGINT,
                                page_url       STRING,  
                                referrer_url   STRING,
                                ip             STRING COMMENT 'IP Address of the User',
                                country        STRING COMMENT 'country of origination')
 COMMENT 'This is the staging page view table'
 ROW FORMAT DELIMITED  
 FIELDS TERMINATED BY '\054'
 STORED AS TEXTFILE
 LOCATION '<hdfs_location>'

复制一个空表:

CREATE TABLE empty_key_value_store 
LIKE key_value_store;
CREATE TABLE empty_key_value_store 
LIKE key_value_store;




2.2 Alter Table

Add Partitions

ALTER TABLE table_name ADD [IF NOT EXISTS] partition_spec [ LOCATION 'location1' ] partition_spec [ LOCATION 'location2' ] ...
 
partition_spec:
  : PARTITION (partition_col = partition_col_value, partition_col = partiton_col_value, ...)
ALTER TABLE table_name ADD [IF NOT EXISTS] partition_spec [ LOCATION 'location1' ] partition_spec [ LOCATION 'location2' ] ...
 
partition_spec:
  : PARTITION (partition_col = partition_col_value, partition_col = partiton_col_value, ...)

 Eg:

ALTER TABLE c02_clickstat_fatdt1 ADD

PARTITION (dt='20101202') location '/user/hive/warehouse/c02_clickstat_fatdt1/part20101202'

PARTITION (dt='20101203') location '/user/hive/warehouse/c02_clickstat_fatdt1/part20101203';

Drop Partitions

ALTER TABLE table_name DROP partition_spec, partition_spec,...
 
ALTER TABLE c02_clickstat_fatdt1 DROP PARTITION (dt='20101202');
ALTER TABLE table_name DROP partition_spec, partition_spec,...
 
ALTER TABLE c02_clickstat_fatdt1 DROP PARTITION (dt='20101202');

Rename Table

ALTER TABLE table_name RENAME TO new_table_name
ALTER TABLE table_name RENAME TO new_table_name

这个命令可以让用户为表更名。数据所在的位置和分区名并不改变。换而言之,老的表名并未“释放”,对老表的更改会改变新表的数据。

Change Column

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]
ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

这个命令可以允许改变列名、数据类型、注释、列位置或者它们的任意组合

Add/Replace Columns

ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...)
ALTER TABLE table_name ADD|REPLACE COLUMNS (col_name data_type [COMMENT col_comment], ...)

ADD是代表新增一字段,字段位置在所有列后面(partition列前);REPLACE则是表示替换表中所有字段。

Eg:

hive> desc xi;
OK 
id      int
cont    string
dw_ins_date     string
Time taken: 0.061 seconds
 
hive> create table xibak like xi;                         
OK
Time taken: 0.157 seconds
 
hive> alter table xibak replace columns (ins_date string);   
OK
Time taken: 0.109 seconds
 
hive> desc xibak;
OK
ins_date        string



2.3 Create View

CREATE VIEW [IF NOT EXISTS] view_name [ (column_name [COMMENT column_comment], ...) ]
[COMMENT view_comment]
[TBLPROPERTIES (property_name = property_value, ...)]
AS SELECT ...
CREATE VIEW [IF NOT EXISTS] view_name [ (column_name [COMMENT column_comment], ...) ]
[COMMENT view_comment]
[TBLPROPERTIES (property_name = property_value, ...)]
AS SELECT ...



2.4 Show

查看表名

SHOW TABLES;
SHOW TABLES;

查看表名,部分匹配

SHOW TABLES 'page.*';
SHOW TABLES '.*view';
SHOW TABLES 'page.*';
SHOW TABLES '.*view';

查看某表的所有Partition,如果没有就报错

SHOW PARTITIONS page_view;
SHOW PARTITIONS page_view;

查看某表结构

DESCRIBE invites;
DESCRIBE invites;

查看分区内容

SELECT a.foo FROM invites a WHERE a.ds ='2008-08-15';
SELECT a.foo FROM invites a WHERE a.ds ='2008-08-15';

查看有限行内容,同Greenplum,用limit关键词

SELECT a.foo FROM invites a limit 3;
SELECT a.foo FROM invites a limit 3;


查看表分区定义

DESCRIBE EXTENDED page_view PARTITION (ds='2008-08-08');
DESCRIBE EXTENDED page_view PARTITION (ds='2008-08-08');



2.5 Load

HIVE装载数据没有做任何转换加载到表中的数据只是进入相应的配置单元表的位置移动数据文件。纯加载操作复制/移动操作。

语法

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

Load 操作只是单纯的复制/移动操作,将数据文件移动到 Hive 表对应的位置。

  • filepath 可以是:
  • 相对路径,例如:project/data1
  • 绝对路径,例如: /user/hive/project/data1
  • 包含模式的完整 URI,例如:hdfs://namenode:9000/user/hive/project/data1      
  • 加载的目标可以是一个表或者分区。如果表包含分区,必须指定每一个分区的分区名。
  • filepath 可以引用一个文件(这种情况下,Hive 会将文件移动到表所对应的目录中)或者是一个目录(在这种情况下,Hive会将目录中的所有文件移动至表所对应的目录中)。
  • 如果指定了 LOCAL,那么:
  • load 命令会去查找本地文件系统中的filepath。如果发现是相对路径,则路径会被解释为相对于当前用户的当前路径。用户也可以为本地文件指定一个完整的 URI,比如:file:///user/hive/project/data1.      
  • load 命令会将 filepath 中的文件复制到目标文件系统中。目标文件系统由表的位置属性决定。被复制的数据文件移动到表的数据对应的位置。
  • 如果没有指定 LOCAL 关键字,如果 filepath 指向的是一个完整的 URI,hive 会直接使用这个 URI。 否则:
  • 如果没有指定 schema 或者 authority,Hive 会使用在 hadoop 配置文件中定义的 schema 和 authority,fs.default.name 指定了 Namenode 的 URI。
  • 如果路径不是绝对的,Hive 相对于 /user/ 进行解释。
  • Hive 会将 filepath 中指定的文件内容移动到 table (或者 partition)所指定的路径中。
  • 如果使用了 OVERWRITE 关键字,则目标表(或者分区)中的内容(如果有)会被删除,然后再将 filepath 指向的文件/目录中的内容添加到表/分区中。
  • 如果目标表(分区)已经有一个文件,并且文件名和 filepath 中的文件名冲突,那么现有的文件会被新文件所替代。

    从本地导入数据到表格并追加原表

LOAD DATA LOCAL INPATH `/tmp/pv_2008-06-08_us.txt` INTO TABLE c02 PARTITION(date='2008-06-08', country='US')
LOAD DATA LOCAL INPATH `/tmp/pv_2008-06-08_us.txt` INTO TABLE c02 PARTITION(date='2008-06-08', country='US')

从本地导入数据到表格并追加记录

LOAD DATA LOCAL INPATH './examples/files/kv1.txt' INTO TABLE pokes;
LOAD DATA LOCAL INPATH './examples/files/kv1.txt' INTO TABLE pokes;

  从hdfs导入数据到表格并覆盖原表

LOAD DATA INPATH '/user/admin/SqlldrDat/CnClickstat/20101101/18/clickstat_gp_fatdt0/0' INTO table c02_clickstat_fatdt1 OVERWRITE PARTITION (dt='20101201');
LOAD DATA INPATH '/user/admin/SqlldrDat/CnClickstat/20101101/18/clickstat_gp_fatdt0/0' INTO table c02_clickstat_fatdt1 OVERWRITE PARTITION (dt='20101201');

关于来源的文本数据的字段间隔符:如果要将自定义间隔符的文件读入一个表,需要通过创建表的语句来指明输入文件间隔符,然后load data到这个表就ok了。



2.6 Insert

Inserting data into Hive Tables from queries

Standard syntax:

INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1 FROM from_statement
INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1 FROM from_statement

 Hive extension (multiple inserts):

FROM from_statement
INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1
[INSERT OVERWRITE TABLE tablename2 [PARTITION ...] select_statement2] ...
FROM from_statement
INSERT OVERWRITE TABLE tablename1 [PARTITION (partcol1=val1, partcol2=val2 ...)] select_statement1
[INSERT OVERWRITE TABLE tablename2 [PARTITION ...] select_statement2] ...

 Hive extension (dynamic partition inserts):

INSERT OVERWRITE TABLE tablename PARTITION (partcol1[=val1], partcol2[=val2] ...) select_statement FROM from_statement
INSERT OVERWRITE TABLE tablename PARTITION (partcol1[=val1], partcol2[=val2] ...) select_statement FROM from_statement

Insert时,from子句既可以放在select子句后,也可以放在insert子句前,下面两句是等价的:

hive> FROM invites a INSERT OVERWRITE TABLE events SELECT a.bar, count(*) WHERE a.foo > 0 GROUP BY a.bar;
hive> INSERT OVERWRITE TABLE events SELECT a.bar, count(*) FROM invites a WHERE a.foo > 0 GROUP BY a.bar;

 插入一条数据:

没有直接插入一条数据的sql,不过可以通过其他方法实现:
    假设有一张表B至少有一条数据,我们想向表A(int,string)中插入一条数据,可以用下面的方法实现:

from B  insert table A select  1,‘abc’ limit 1;
 from B  insert table A select  1,‘abc’ limit 1;

    我觉得hive好像不能够插入一个记录,因为每次你写insert语句的时候都是要将整个表的值overwrite。我想这个应该是与hive的storage layer是有关系的,因为它的存储层是HDFS,插入一个数据要全表扫描,还不如用整个表的替换来的快些。

          Hive不支持一条一条的用insert语句进行插入操作,也不支持update的操作。数据是以load的方式,加载到建立好的表中。数据一旦导入,则不可修改。要么drop掉整个表,要么建立新的表,导入新的数据。    

Writing data into filesystem from queries

  Standard syntax:

INSERT OVERWRITE [LOCAL] DIRECTORY directory1 SELECT ... FROM ...
INSERT OVERWRITE [LOCAL] DIRECTORY directory1 SELECT ... FROM ...

 Hive extension (multiple inserts):

FROM from_statement
INSERT OVERWRITE [LOCAL] DIRECTORY directory1 select_statement1
[INSERT OVERWRITE [LOCAL] DIRECTORY directory2 select_statement2] ...
FROM from_statement
INSERT OVERWRITE [LOCAL] DIRECTORY directory1 select_statement1
[INSERT OVERWRITE [LOCAL] DIRECTORY directory2 select_statement2] ...

导出文件到本地

INSERT OVERWRITE LOCAL DIRECTORY '/tmp/local_out' SELECT a.* FROM pokes a;
INSERT OVERWRITE LOCAL DIRECTORY '/tmp/local_out' SELECT a.* FROM pokes a;

导出文件到HDFS

INSERT OVERWRITE DIRECTORY '/user/admin/SqlldrDat/CnClickstat/20101101/19/clickstat_gp_fatdt0/0' SELECT a.* FROM c02_clickstat_fatdt1 a WHERE dt=’20101201’;
INSERT OVERWRITE DIRECTORY '/user/admin/SqlldrDat/CnClickstat/20101101/19/clickstat_gp_fatdt0/0' SELECT a.* FROM c02_clickstat_fatdt1 a WHERE dt=’20101201’;

一个源可以同时插入到多个目标表或目标文件,多目标insert可以用一句话来完成

FROM src
  INSERT OVERWRITE TABLE dest1  
SELECT src.* WHERE src.key < 100
  INSERT OVERWRITE TABLE dest2  
SELECT src.key, src.value WHERE src.key >= 100 and src.key < 200
  INSERT OVERWRITE TABLE dest3 PARTITION(ds='2008-04-08', hr='12')  
SELECT src.key WHERE src.key >= 200 and src.key < 300
  INSERT OVERWRITE LOCAL DIRECTORY '/tmp/dest4.out'  
SELECT src.value WHERE src.key >= 300;
FROM src
  INSERT OVERWRITE TABLE dest1  
SELECT src.* WHERE src.key < 100
  INSERT OVERWRITE TABLE dest2  
SELECT src.key, src.value WHERE src.key >= 100 and src.key < 200
  INSERT OVERWRITE TABLE dest3 PARTITION(ds='2008-04-08', hr='12')  
SELECT src.key WHERE src.key >= 200 and src.key < 300
  INSERT OVERWRITE LOCAL DIRECTORY '/tmp/dest4.out'  
SELECT src.value WHERE src.key >= 300;

Eg:

from xi  
insert overwrite  table test2 select  '1,2,3' limit 1 
insert overwrite  table d select  '4,5,6' limit 1;
from xi  
insert overwrite  table test2 select  '1,2,3' limit 1 
insert overwrite  table d select  '4,5,6' limit 1;




2.7 Cli

Hive Command line Options

$HIVE_HOME/bin/hive是一个shell工具,它可以用来运行于交互或批处理方式配置单元查询。

语法:

Usage: hive [-hiveconf x=y]* [<-i filename>]* [<-f filename>|<-e query-string>] [-S]
 
  -i <filename>             Initialization Sql from file (executed automatically and silently before any other commands)
  -e 'quoted query string'  Sql from command line
  -f <filename>             Sql from file
  -S                        Silent mode in interactive shell where only data is emitted
  -hiveconf x=y             Use this to set hive/hadoop configuration variables. 
  
   -e and -f cannot be specified together. In the absence of these options, interactive shell is started.  
   However, -i can be used with any other options.  Multiple instances of -i can be used to execute multiple init scripts.
 
   To see this usage help, run hive -h

  运行一个查询:

$HIVE_HOME/bin/ hive -e 'select count(*) from c02_clickstat_fatdt1'
$HIVE_HOME/bin/ hive -e 'select count(*) from c02_clickstat_fatdt1'

Example of setting hive configuration variables

$HIVE_HOME/bin/hive -e 'select a.col from tab1 a' -hiveconf hive.exec.scratchdir=/home/my/hive_scratch  -hiveconf mapred.reduce.tasks=32

将查询结果导出到一个文件

HIVE_HOME/bin/hive -S -e 'select count(*) from c02_clickstat_fatdt1' > a.txt

运行一个脚本

HIVE_HOME/bin/hive -f /home/my/hive-script.sql
HIVE_HOME/bin/hive -f /home/my/hive-script.sql

  Example of running an initialization script before entering interactive mode

HIVE_HOME/bin/hive -i /home/my/hive-init.sql
HIVE_HOME/bin/hive -i /home/my/hive-init.sql

Hive interactive Shell Command

Command

Description

quit

使用 quit or exit 退出

set <key>=<value>

使用这个方式来设置特定的配置变量的值。有一点需要注意的是,如果你拼错了变量名,CLI将不会显示错误。

set

这将打印的配置变量,如果没有指定变量则由显示HIVE和用户变量。如set I 则显示i的值,set则显示hive内部变量值

set -v

This will give all possible hadoop/hive configuration   variables.

add FILE <value> <value>*

Adds a file to the list of resources.

list FILE

list all the resources already added

list FILE <value>*

Check given resources are already added or not.

! <cmd>

execute a shell command from hive shell

dfs <dfs command>

execute dfs command command from hive shell

<query string>

executes hive query and prints results to stdout

Eg:

hive> set  i=32;
  hive> set i;
  hive> select a.* from xiaojun a;
  hive> !ls;
  hive> dfs -ls;
  hive> set  i=32;
  hive> set i;
  hive> select a.* from xiaojun a;
  hive> !ls;
  hive> dfs -ls;

还可以这样用

hive> set $i='121.61.99.14.128160791368.5';
hive> select count(*) from c02_clickstat_fatdt1 where cookie_id=$i;
11

Hive Resources

Hive can manage the addition of resources to a session where those resources need to be made available at query execution time. Any locally accessible file can be added to the session. Once a file is added to a session, hive query can refer to this file by its name (in map/reduce/transform clauses) and this file is available locally at execution time on the entire hadoop cluster. Hive uses Hadoop's Distributed Cache to distribute the added files to all the machines in the cluster at query execution time.

Usage:

·          ADD { FILE[S] | JAR[S] | ARCHIVE[S] } <filepath1> [<filepath2>]*

·         LIST { FILE[S] | JAR[S] | ARCHIVE[S] } [<filepath1> <filepath2> ..]

·         DELETE { FILE[S] | JAR[S] | ARCHIVE[S] } [<filepath1> <filepath2> ..]

  • FILE resources are just added to the distributed cache. Typically,      this might be something like a transform script to be executed.
  • JAR resources are also added to the Java classpath. This is required      in order to reference objects they contain such as UDF's.
  • ARCHIVE resources are automatically unarchived as part of      distributing them.

Example:

·           hive> add FILE /tmp/tt.py;

·         hive> list FILES;

·           /tmp/tt.py

·         hive> from networks a  MAP a.networkid USING 'python tt.py' as nn where a.ds = '2009-01-04' limit  10;

It is not neccessary to add files to the session if the files used in a transform script are already available on all machines in the hadoop cluster using the same path name. For example:

  • ... MAP a.networkid USING 'wc -l' ...: here wc is an executable      available on all machines
  • ... MAP a.networkid USING '/home/nfsserv1/hadoopscripts/tt.py' ...:      here tt.py may be accessible via a nfs mount point that's configured      identically on all the cluster nodes

调用python、shell等语言

如下面这句sql就是借用了weekday_mapper.py对数据进行了处理

CREATE TABLE u_data_new (
  userid INT,
  movieid INT,
  rating INT,
  weekday INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t';
 
add FILE weekday_mapper.py;
 
INSERT OVERWRITE TABLE u_data_new
SELECT
  TRANSFORM (userid, movieid, rating, unixtime)
  USING 'python weekday_mapper.py'
  AS (userid, movieid, rating, weekday)
FROM u_data;
CREATE TABLE u_data_new (
  userid INT,
  movieid INT,
  rating INT,
  weekday INT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t';
 
add FILE weekday_mapper.py;
 
INSERT OVERWRITE TABLE u_data_new
SELECT
  TRANSFORM (userid, movieid, rating, unixtime)
  USING 'python weekday_mapper.py'
  AS (userid, movieid, rating, weekday)
FROM u_data;

,其中weekday_mapper.py内容如下

import sys
import datetime
 
for line in sys.stdin:
  line = line.strip()
  userid, movieid, rating, unixtime = line.split('\t')
  weekday = datetime.datetime.fromtimestamp(float(unixtime)).isoweekday()
  print '\t'.join([userid, movieid, rating, str(weekday)])
import sys
import datetime
 
for line in sys.stdin:
  line = line.strip()
  userid, movieid, rating, unixtime = line.split('\t')
  weekday = datetime.datetime.fromtimestamp(float(unixtime)).isoweekday()
  print '\t'.join([userid, movieid, rating, str(weekday)])

如下面的例子则是使用了shell的cat命令来处理数据

FROM invites a INSERT OVERWRITE TABLE events 
SELECT TRANSFORM(a.foo, a.bar) AS (oof, rab) USING '/bin/cat'
 WHERE a.ds > '2008-08-09';
FROM invites a INSERT OVERWRITE TABLE events 
SELECT TRANSFORM(a.foo, a.bar) AS (oof, rab) USING '/bin/cat'
 WHERE a.ds > '2008-08-09';



2.8 DROP

    删除一个内部表的同时会同时删除表的元数据和数据。删除一个外部表,只删除元数据而保留数据。



2.9 other

 Limit

    Limit 可以限制查询的记录数。查询的结果是随机选择的。下面的查询语句从 t1 表中随机查询5条记录:

SELECT * FROM t1 LIMIT 5
SELECT * FROM t1 LIMIT 5


Top k

    下面的查询语句查询销售记录最大的 5 个销售代表。

SET mapred.reduce.tasks = 1
  SELECT * FROM sales SORT BY amount DESC LIMIT 5
SET mapred.reduce.tasks = 1
  SELECT * FROM sales SORT BY amount DESC LIMIT 5

 

REGEX Column Specification

    SELECT 语句可以使用正则表达式做列选择,下面的语句查询除了 ds 和 hr 之外的所有列:

SELECT `(ds|hr)?+.+` FROM sales
SELECT `(ds|hr)?+.+` FROM sales