Hive學(xué)習(xí)
Author : Shan Jia-jun
Date : 2016-09-18
hive把數(shù)據(jù)組織為表,通過這種方式為存儲在HDFS上的數(shù)據(jù)賦予結(jié)構(gòu)
元數(shù)據(jù)存儲在metastore數(shù)據(jù)庫中春锋。
hive 外殼環(huán)境
hive > show tables;
#列出hive的數(shù)據(jù)列表
#交互式環(huán)境
hive > show databases;
#列出所有的數(shù)據(jù)庫材泄;
hive > show tables in dbname;
#列出某個數(shù)據(jù)庫中的表引矩;
hive > show tables like 'h*';
#使用正則表達(dá)式列出某個以h開頭的表的名字黍翎;
hive > describe databases dbname;
$ hive -f script.q
#使用-f選項(xiàng)可以運(yùn)行指定文件中的命令
#也可以使用非交互式環(huán)境
$ hive -e 'select * from dummy'
#對于較短的腳本熔脂,可以使用-e選項(xiàng)在行內(nèi)嵌入命令
- 建立一個較小的數(shù)據(jù)表用于測試查詢
$ echo 'x' > dummy.txt
$ hive -e "create table dummy (value string);load data local inpath '/home/shanjiajun/dummy.txt' into table dummy;"
如果不想將操作運(yùn)行信息打印到標(biāo)準(zhǔn)輸出中眉睹,這時候可以使用-S選項(xiàng),不顯示打印運(yùn)行的時間信息飘言;
創(chuàng)建一個表并導(dǎo)入數(shù)據(jù)
create table records (year string, temperature int, quality int)
row format delimited fields terminated by '\t';
#該表聲明的是數(shù)據(jù)文件的每一行是由制表符分隔的文本
load date local inpath 'input/ncdc/micro-tab/sample.txt' overwrite into table records;
#這一個命令告訴hive把指定的本地文件放進(jìn)倉庫目錄中衣形。
#但是這個操作并不解析文件或把它存儲為內(nèi)部數(shù)據(jù)庫格式,因?yàn)閔ive并不強(qiáng)制使用任何指定文件格式姿鸿。
#文件以原樣逐字存儲谆吴,hive并不會對文件進(jìn)行修改。local為從本地上傳數(shù)據(jù)苛预。overwrite為覆蓋上傳.
#在hive的倉庫目錄中句狼,表存儲為目錄。HDFS的數(shù)據(jù)表存儲目錄為/user/hive/warehouse
刪除表
$hive -e 'drop table if exists 表名'
#刪除hive中的一個表
#注意:使用hive命令刪除表后热某,但是上傳的數(shù)據(jù)并不會被刪除腻菇,僅僅只是刪除了一個表的目錄,需要手動刪除HDFS中的數(shù)據(jù)
更新
hive 不支持更新(或刪除)昔馋,但支持insert into ,所以可以向現(xiàn)有表中增加新的行筹吐。
多數(shù)據(jù)庫/模式支持
hive 支持創(chuàng)建多個數(shù)據(jù)庫或模式,可用的命令包括 SHOW DATABASES秘遏、CREATE DATABASE dbname丘薛、user dbname 以及DROP DATABASE dbname 這樣的語句。如果沒有明確指明數(shù)據(jù)庫邦危,那么所指定的是在default數(shù)據(jù)庫中的表
托管表和外部表
#對于托管表洋侨,加載數(shù)據(jù)到托管表時舍扰,hive把數(shù)據(jù)移到倉庫目錄。例如:
hive > CREATE TABLE managed_table (dummy STRING);
hive > LOAD DATA INPATH '/user/tom/data.txt' INTO table managed_table;
#此時load把文件從hdfs:/user/tom/data.txt 移動到hdfs: /user/hive/warehouse/managed_table.
#對于外部表而言希坚,外部數(shù)據(jù)的位置需要在創(chuàng)建表的時候聲明:
CREATE EXTERNAL TABLE external_table (dummy STRING)
LOCATION '/user/tom/external_table';
LOAD DATA INPATH '/user/tom/data.txt' INTO TABLE external_table;
#只有源和目標(biāo)在同一個文件系統(tǒng)中移動才會成功边苹。
#當(dāng)然,作為特例裁僧,如果用了LOCAL關(guān)鍵字个束,hive會吧本地文件系統(tǒng)的數(shù)據(jù)復(fù)制到hive的倉庫目錄。在其他情況下聊疲,最好把LOAD視為一個移動操作播急。
#使用EXTERNAL關(guān)鍵字以后,hive知道數(shù)據(jù)并不由自己管售睹,因此不會把數(shù)據(jù)移動到自己的倉庫目錄桩警。
#丟棄外部表時,hive不會碰數(shù)據(jù)昌妹,而只會刪除元數(shù)據(jù)捶枢。
建立外部分區(qū)表
創(chuàng)建一個外部表:
create external table user_action_201608
(type STING,userid string,region string,action string)
partitioned by (day string)
row format delimited
fields terminated by '|'
location '/cucrz/data/look/1901/2016/08';
修改表創(chuàng)建分區(qū)
alter table user_action_201608 add partition (day='01')
location '01';
alter table user_action_201608 add partition (day='02')
location '02';
alter table user_action_201608 add partition (day='03')
location '03';
...
#查詢:
select * from user_action_201608 limit 10;