hive是hdfs上的數(shù)據(jù)倉庫譬胎,能夠?qū)⒁粋€個大文件有效地管理起來,并對其進(jìn)行統(tǒng)計分析。數(shù)據(jù)倉庫看待數(shù)據(jù)的方式與常見的數(shù)據(jù)庫是完全不同的,它的最小粒度是文件而不是單條數(shù)據(jù)吓著。hive一般在hdfs上的路徑為/user/hive/warehouse蒙谓,而hive中的數(shù)據(jù)庫(如demo)的路徑就是/user/hive/warehouse/demo.db造烁,在往下就是表的路徑如:/user/hive/warehouse/demo.db/test搞动。管理hive上的數(shù)據(jù)分為兩部分:定義數(shù)據(jù)以及操縱數(shù)據(jù)。
基本命令
切換數(shù)據(jù)庫:use 數(shù)據(jù)庫名;
顯示當(dāng)前數(shù)據(jù)庫中的所有變:show tables;
查看表結(jié)構(gòu):desc 表名;
查看建表語句:show create table 表名;
數(shù)據(jù)定義語句(DDL)
創(chuàng)建表
完整語句
CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.]table_name -- (Note: TEMPORARY available in Hive 0.14.0 and later)
[(col_name data_type [COMMENT col_comment], ... [constraint_specification])]
[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]
[SKEWED BY (col_name, col_name, ...) -- (Note: Available in Hive 0.10.0 and later)]
ON ((col_value, col_value, ...), (col_value, col_value, ...), ...)
[STORED AS DIRECTORIES]
[
[ROW FORMAT row_format]
[STORED AS file_format]
| STORED BY 'storage.handler.class.name' [WITH SERDEPROPERTIES (...)] -- (Note: Available in Hive 0.6.0 and later)
]
[LOCATION hdfs_path]
[TBLPROPERTIES (property_name=property_value, ...)] -- (Note: Available in Hive 0.6.0 and later)
[AS select_statement]; -- (Note: Available in Hive 0.5.0 and later; not supported for external tables)
- hive可以創(chuàng)建臨時表[temporary]驮履,臨時表在當(dāng)前會話結(jié)束時(如關(guān)閉hive客戶端)會被自動刪除鱼辙。
- hive可以外部的映射表[external],即hive并不將這些數(shù)據(jù)存儲在自己的hdfs路徑中玫镐,而只保存表的元數(shù)據(jù)倒戏。這樣hive便可訪問更多的數(shù)據(jù)源,如hbase恐似。
- hive可以直接將select語句的結(jié)果保存為一個表:create table t2 as select * from t1;
- hive的基本單元是文件杜跷,那么在創(chuàng)建表的時候可以指定文件中每行數(shù)據(jù)的分隔符,即按該分割符分割后即為表的各列:create table t(c1 string, c2 string) row format delimited fields terminated by '\t'矫夷。
- hive中的表就是hdfs上的一個路徑葛闷,在創(chuàng)建表時可以在其下繼續(xù)創(chuàng)建文件目錄,這樣的好處就是在查詢時可以只訪問一些指定的目錄來提高性能双藕。create table t1(id string) partitioned by (year string, month string)淑趾,這樣t1路徑下就是year的文件夾,而year的每個值路徑下還有month文件夾忧陪,如圖所示:
修改表
表重命名:alter table 原表名 rename to 新表名
刪除分區(qū):alter table xx drop partition (xx='')
數(shù)據(jù)操縱語言(DML)
加載數(shù)據(jù)
1)從本地加載: load data local inpath 'data/t1' into table t1;
2)從HDFS轉(zhuǎn)移:load data inpath '/user/hive/project/data1' into table xxx;