Hive 的基础使用

来源:互联网 发布:梦里花落知多少豆瓣 编辑:程序博客网 时间:2024/05/29 18:58

在创建一个表baobei_info后,

给baobei_info 插入一些数据,他并不支持insert 这样的关系型数据库的操作,

首先:我们在创建表时,row 分割符是使有 ":",在file文件夹下新建一个baobei_info.txt 格式如:

1:100

2:90

我们把这个baobei_info.txt 文件导入到数据库hive 表baobei_info 中。命令如下:

load data local inpath '/home/liucheng/file/baobei_info.txt'   overwrite into table baobei_info;

如图:


这个时候,这个文件已经上传到了HDFS 下 目录为/user/hive/warehouse/baobei_info/baobei_info.txt

如图:


注:而在mysql数据库hive 中的表下。并没有对应的数据存储。

先在hdfs 下创建一个hiveinput 的目录
./bin/hadoop fs -mkdir hiveinput   -- 创建hiveinput目当
./bin/hadoop fs -ls        -- 查看是否创建成功
// 创建一个外联表,存储在hdfs 文件的hiveinput目录下

create external table page_view(viewTime INT,userid BIGINT,page_url STRING,referrer_url STRING,ip STRING COMMENT 'ip address of user',country STRING COMMENT 'country of china')comment 'this is test table'row format delimited fields terminated by '\054'stored as textfilelocation '/user/localhost/hiveinput';
1\054121\054http://baidu.com\054http://203.123.123.123:9090/index.jsp\054203.203.203.203\054china2\054122\054http://baidu.com\054http://203.123.123.124:9090/index.jsp\054203.203.203.203\054usa3\054123\054http://baidu.com\054http://203.123.123.125:9090/index.jsp\054203.203.203.203 japan

load data local inpath '/home/liucheng/file/page_view.txt' overwrite into table page_view; -- 导入数据到page_view 表中select * from page_view; 


在50070的地址上看,数据已经成功导入到/user/localhost/hiveinput/page_view/page_view.txt
而且对容也正确.
在google 一下,说是分割符的问题,所以又把上边的表删除,同时也要删除hdfs 下的文件(/user/localhost/hiveinput/page_view/page_view.txt)。
因为在创建表的时候是,external 外联表。
在HDFS下创建hiveinput目录,如上所说。
创建表:代码如下: 分割符 为空格 ' '
create external table page_view(viewTime INT,userid BIGINT,page_url STRING,referrer_url STRING,ip STRING COMMENT 'ip address of user',country STRING COMMENT 'country of china')comment 'this is test table'row format delimited fields terminated by '  'stored as textfilelocation '/user/localhost/hiveinput'; 

创建成功,导入数据 如上说示
1 121 http://baidu.com http://203.123.123.123:9090/index.jsp 203.203.203.203 china2 122 http://baidu.com http://203.123.123.124:9090/index.jsp 203.203.203.203 usa3 123 http://baidu.com http://203.123.123.125:9090/index.jsp 203.203.203.203 japan

导入成功显示数据;

注:这个null 的显示是解决了,又引出了一个新的问题,假设这个数据是存在的,就是用\540 做为分割的,那么访如何解决。

hive官方提供两种导入数据的方式

  1 从表中导入:

 insert overwrite table test

 select * from test2;

 2 从文件导入:

   2.1 从本地文件导入:

      load data local inpath '/hadoop/aa.txt' overwrite into table test11 

   2.2  从hdfs导入

      load data inpath '/hadoop/aa.txt' overwrite into table test11 

3 导入文件的列划分

    在建表的时候可以指定划分的字符 如:

     create table test11(id int,name string)

     row format delimited

     fields terminated by '\;' 以分号划分文件的列这样导入的数据文件就如同 1;张三 这种格式。

4 到出数据

   一般用 :bin/hive -e "select * from test" >> res.csv 

   或者:bin/hive -f sql.q >> res.csv (其中文件sql.q写入你想要执行的查询语句)