hive基礎入門

1.Hive
    在hadoop屬於數據倉庫的角色,能夠管理hadoop中的角色,同時可以查詢hadoop中的數據.
    Hive本質上講他是一個sql解析引擎,hive可以把sql查詢轉換爲MapReduce中的job來運行.
    Hive有一套映射工具,可以把sql轉換爲MapReduce中的Job,可以把sql中的表字段轉換爲HDFS中的
    文件(夾),以及文件中的列,這套映射工具我們稱之爲metastore(元存儲).一般存放在deroy,mysql中
2、安裝hive(客戶端工具)
    .hive在hdfs中的默認位置是/user/hive/warehouse/
    .可以修改默認hive在hdfs下的數據存儲位置
        hive的conf中的hive-site.xml(這個文件是被重新命名的文件,原文件名不叫這個,
        在下面修改了,文件名,才做這一步的操作的)
        <property>
            <name>hive.metastore.warehouse.dir</name>
            //默認數據庫位置
            <value>/user/hive/warehouse</value>
            <description>location of default database for the warehouse</description>
        </property>
        
    2.1 解壓縮
        tar -zxvf hive-0.9.0.tar.gz
    2.2 重命名
        [root@hadoop0 Downloads]# mv hive-0.9.0 hive
    2.3 移動到/usr/local/目錄下
        [root@hadoop0 Downloads]# mv hive /usr/local/
    2.4 刪除gz後綴的文件(可選步驟) 
        [root@hadoop0 local]# rm -rf *.gz
    2.5 hive設置到環境變量中
        [root@hadoop0 local]# vi /etc/profile       //修改
        export HIVE_HOME=/usr/local/hive
        export PATH=.:$HADOOP_HOME/bin:$HIVE_HOME/bin:$PIG_HOME/bin:$ZOOKEEPER_HOME/bin:
        $HBASE_HOME/bin:$JAVA_HOME/bin:$PATH
        [root@hadoop0 local]# source /etc/profile   讓配置立即生效
    2.6 重命名hive的conf下面的配置文件
        [root@hadoop0 conf]# mv hive-default.xml.template hive-site.xml     //修改文件名
        [root@hadoop0 conf]# mv hive-env.sh.template hive-env.sh            //修改文件名
        [root@hadoop0 conf]# ls
        hive-env.sh                          hive-log4j.properties.template
        hive-exec-log4j.properties.template  hive-site.xml
    2.7 修改配置文件內容
        .修改hadoop下面的配置文件
        [root@hadoop0 conf]# vi ../../hadoop/conf/hadoop-env.sh
            修改內容
                 export HADOOP_CLASSPATH=.:$CLASSPATH:$HADOOP_CLASSPATH:$HADOOP_HOME/bin
        .修改$HIVE_HOME/hive/bin/hive-conf.xml文件
            [root@hadoop0 conf]# vi ../bin/hive-config.sh
            增加內容
            export JAVA_HOME=/usr/local/jdk
            export HIVE_HOME=/usr/local/hive
            export HADOOP_HOME=/usr/local/hadoop
        ********************************************************
        .hive在hdfs中的默認位置是/user/hive/warehouse/
        .可以修改默認hive在hdfs下的數據存儲位置
             修改hive的conf下的hive-site.xml(這個文件是被重新命名的文件,原文件名不叫這個,
            在下面修改了,文件名,才做這一步的操作的)
        <property>
            <name>hive.metastore.warehouse.dir</name>
            //默認數據庫位置
            <value>/user/hive/warehouse</value>
            <description>location of default database for the warehouse</description>
        </property>
    2.8 使用hive(必須保證hadoop是正在運行的)
        [root@hadoop0 bin]# ls  //進入hive的bin目錄
        ext  hive  hive-config.sh
        [root@hadoop0 bin]# hive  執行hive就可以進入他的終端了
    2.9 使用mysql數據庫命令可以操作hive
        hive> show databases;   //查看數據庫列表
        hive> use default;      //使用表
        hive> show tables;      //查看有多少張表
        hive> create table t1(id string);       
            //有時候會報錯,是因爲hadoop的安全模式是開啓的
            hadoop dfsadmin -safemode leave,先關閉安全模式,才能創建表成功
        hive> show tables;      //驗證
        hive> select * from t1;     //查詢表內容
    2.9.1 hive是存儲在HDFS文件系統中的
        .http://hadoop1:50075/browseDirectory.jsp?namenodeInfoPort=50070&dir=/ 中可以查看
        .user目錄裏面有hive的數據文件
3.0 安裝mysql數據庫做爲hive的數據倉庫
    3.1 不同hive客戶端訪問同一資源就會報錯
        .hive只能用一個客戶端打開(一個用戶訪問資源)
        derby.log  ext  hive  hive-config.sh  metastore_db(一般不會用db,測試使用)
        .實際開發中都是使用mysql,不會使用自帶的db數據庫
    3.2 刪除hive的默認倉庫
        [root@hadoop0 bin]# rm -rf metastore_db/    //刪除hive的db數據文件
        [root@hadoop0 conf]# vi hive-site.xml       //修改hive數據庫默認存儲位置
                    hive.metastore.warehouse.dir    這一項修改
        ******************************************開始安裝********************
        (1) 刪除linux默認安裝的mysql數據庫
            [root@hadoop0 conf]# rpm -qa | grep mysql   //查看是否安裝了mysql
            mysql-libs-5.1.66-2.el6_3.i686
            [root@hadoop0 conf]# rpm -e mysql-libs-5.1.66-2.el6_3.i686      //刪除mysql
            error: Failed dependencies:     //有依賴不能刪除
            libmysqlclient.so.16 is needed by (installed) postfix-2:2.6.6-2.2.el6_1.i686
            libmysqlclient.so.16(libmysqlclient_16) is needed by (installed) postfix
            -2:2.6.6-2.2.el6_1.i686
            mysql-libs is needed by (installed) postfix-2:2.6.6-2.2.el6_1.i686
            [root@hadoop0 conf]# rpm -e mysql-libs-5.1.66-2.el6_3.i686 --nodeps   //強制刪除
            [root@hadoop0 conf]# rpm -qa | grep mysql       //驗證是否刪除
rpm -qa | grep -i mysql
            .把需要安裝文件拷貝到/root/Dowloads中
            [root@hadoop0 conf]# cd /root/Downloads
            [root@hadoop0 Downloads]# ls
            MySQL-client-5.5.31-2.el6.i686.rpm  //客戶端文件
            mysql-connector-java-5.1.10.jar     //驅動
            MySQL-server-5.5.31-2.el6.i686.rpm  //服務端文件
        (2) 執行命令rpm -i MySQL-server-5.5.31-2.el6.i686.rpm安裝mysql服務端
            [root@hadoop0 Downloads]# rpm -i MySQL-server-5.5.31-2.el6.i686.rpm
        (3) 啓動mysql服務端
            mysqld_safe &   //後臺啓動
        (4) 安裝mysql客戶端
            [root@hadoop0 Downloads]# rpm -i MySQL-client-5.5.31-2.el6.i686.rpm
        (5) 修改root用戶密碼
            [root@hadoop0 Downloads]# mysql_secure_installation     //修改數據庫配置信息


            NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
            SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!


            In order to log into MySQL to secure it, we'll need the current
            password for the root user.  If you've just installed MySQL, and
            you haven't set the root password yet, the password will be blank,
            so you should just press enter here.


            Enter current password for root (enter for none):   //當前密碼,第一次使用爲null
                OK, successfully used password, moving on...


                Setting the root password ensures that nobody can log into the MySQL
                root user without the proper authorisation.


                Set root password? [Y/n] Y      //設置密碼
                New password:                   /admin
                Re-enter new password:          //admin
                Password updated successfully!
                Reloading privilege tables..
                ... Success!


                By default, a MySQL installation has an anonymous user, allowing anyone
                to log into MySQL without having to have a user account created for
                them.  This is intended only for testing, and to make the installation
                go a bit smoother.  You should remove them before moving into a
                production environment.


                Remove anonymous users? [Y/n] n     //是否刪除匿名用戶
                ... skipping.


                Normally, root should only be allowed to connect from 'localhost'.  This
                ensures that someone cannot guess at the root password from the network.


                Disallow root login remotely? [Y/n] n       //是否允許遠程登錄
                ... skipping.


                By default, MySQL comes with a database named 'test' that anyone can
                access.  This is also intended only for testing, and should be removed
                before moving into a production environment.


                Remove test database and access to it? [Y/n] n  //是否刪除測試數據庫
                ... skipping.


                Reloading the privilege tables will ensure that all changes made so far
                will take effect immediately.


                Reload privilege tables now? [Y/n] Y        //重新加載權限表
                ... Success!


                Cleaning up...


                All done!  If you've completed all of the above steps, your MySQL
                installation should now be secure.


                Thanks for using MySQL!
            
                登錄mysql數據庫驗證
                [root@hadoop0 Downloads]# mysql -uroot -padmin
            
    3.4 使用mysql作爲hive的metastore(數據倉庫)
        (1) 把mysql的jdbc驅動放置到hive的lib目錄下
           [root@hadoop0 Downloads]# cp mysql-connector-java-5.1.10.jar /usr/local/hive/lib/
        (2) 修改hive-site.xml文件
           <property>
           <name>javax.jdo.option.ConnectionURL</name>
           //連接地址
           <value>jdbc:mysql://hadoop0:3306/hive?createDatabaseIfNotExist=true</value>
           </property>
           <property>
           <name>javax.jdo.option.ConnectionDriverName</name>
           //mysql驅動
           <value>com.mysql.jdbc.Driver</value>
           </property>
           <property>
           <name>javax.jdo.option.ConnectionUserName</name>
           //用戶名
           <value>root</value>
           </property>
           <property>
           <name>javax.jdo.option.ConnectionPassword</name>
           //用戶密碼
           <value>admin</value>
           </property>
        (3) 進入hive的bin目錄下
            [root@hadoop0 bin]# ls
            derby.log  ext  hive  hive-config.sh
            [root@hadoop0 bin]# hive 運行hive
            hive> show databases;    //查看數據庫
            hive> use default;      //使用表
        (4) 遠程連接一下mysql在windows下
            .這個時候會報錯,因爲mysql默認是不能遠程連接的
            [root@hadoop0 bin]# mysql -uroot -padmin        //登錄mysql
            mysql> grant all on hive.* to 'root'@'%' identified by 'admin'; //授權root
            Query OK, 0 rows affected (0.09 sec)    //在任何位置(%)都可以遠程登錄
            mysql> flush privileges;                //刷新權限
        (5) 連接成功,使用的是SQLyog數據庫可視化軟件


4、hive幾種表的操作
4.1 內部表(受控表)
    create table t1(id int);    //創建一張內部表
    http://hadoop1:50075/browseDirectory.jsp?dir=%2Fhive&namenodeInfoPort=50070 查看錶
    //下面語句中加上的local,指的是從hdfs下面找,如果不加local,那麼就會報錯
    hive>load data local inpath '/root/id' into table t1;    //加載文件中的數據到t1表中
    hive>select * from t1;          //可以查看加載進來的數據


4.1.0 基於hadoop2.0的HA模式下加載數據


    hive>load data inpath 'hdfs://cluster1/root/id' into table t4;
    
4.1.1 感覺加載進來的文件和我們put到hdfs中的文件類似?
    http://hadoop1:50075/browseDirectory.jsp?dir=%2Fhive%2Ft1&namenodeInfoPort=50070
    [root@hadoop0 ~]# hadoop fs -put id /hive/t1/id2        //put一下這個id文件,改名爲id2
    ***********************************************************
    結論就是加載可以有兩種方式
    hive的load語句,或者hadoop的put方式,加入文件數據,hive都是認的
4.1.2 創建一張表t2
    告訴行的格式,以製表符分隔
    hive>create table t2(id int,name string) row format delimited fields terminated by '\t';
    在hdfs系統下創建一個stu文件,裏面有相應的字段值對應表
    [root@hadoop0 ~]# hadoop fs -put stu /hive/t2   上傳這個文件數據到hive數據倉庫t2表中
    hive> seletc id from t2;或者seletc * from t2;   //驗證
4.2 分區表 
    創建分區表,天來劃分
    hive>create table t3(id int,name string) partitioned by(day int);    //天來劃分
    加載數據到分區表,按天加載數據
    hive>load data local inpath '/root/id' into table t3 partition (day=22);//加載數據
    hive>seletc * from t3 where day=22;     //驗證
    //分區表都是使用分區字段來查詢,下面的情況
    hive>seletc * from t3 where id=1;       //他會把所有分區字段裏面id=1的數據查詢出來
4.3 桶表
    桶表是對數據進行哈希取值,然後放到不同文件中存儲。
    創建表
    create table bucket_table(id string) clustered by(id) into 4 buckets;
    加載數據
    set hive.enforce.bucketing = true;
    insert into table bucket_table select name from stu;
    insert overwrite table bucket_table select name from stu;
    數據加載到桶表時,會對字段取hash值,然後與桶的數量取模。把數據放到對應的文件中。


    抽樣查詢
    select * from bucket_table tablesample(bucket 1 out of 4 on id);
    例子:
        create table t4(id int) clustered by(id) into 4 buckets;    //把數據分到4個桶中
        //加載數據到桶表
        set hive.enforce.bucketing = true;
   insert into table t4 select id from t3;     //通過mapreduce運算把表中的數據放到桶中
        //通過地址查看目錄結構,類似這樣的結構,裏面的內容是通過hash編碼某個標準後存放的
        http://hadoop2:50075/browseDirectory.jsp?dir=%2Fhive%2Ft4&namenodeInfoPort=50070
        000000_0    .數據都有一定的特點,非常有可能相等數據
        000001_0    .可以用來抽樣調查
        000002_0    .桶表僅僅在做錶鏈接的時候用
        000003_0
5、 外部表
    創建數據文件external_table.dat


    創建表
    hive>create external table external_table1 (key string) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' location '/home/external';
    在HDFS創建目錄/home/external
    #hadoop fs -put /home/external_table.dat /home/external


    加載數據
    LOAD DATA INPATH '/home/external_table1.dat' INTO TABLE external_table1;


    查看數據
    select * from external_table
    select count(*) from external_table


    刪除表 
    drop table external_table
例子:
    [root@hadoop0 ~]# hadoop fs -put id /external/id    //從本地put一個文件到hdfs
    //外部目錄指定數據在哪裏,所以不需要指定路徑,直接就可以查詢
    hive>create external table t5(id int) location '/external';  //創建一張外部表
    hive>seletc * from t5;       //驗證
    hive>drop table t5;     //刪除表,只是刪除表定義,二指定的數據文件不會刪除
    
6、視圖
    




注: 可以使用limit操作,限定返回結果
    hive>seletc * from t1 limit 5;   //返回5條結果
    可以使用order by xxx
7、java遠程hive
    .需要啓動,不然不能遠程hive
        hive --service hiveserver >/dev/null  2>/dev/null &
    .java客戶端代碼
    public class App {
   public static void main(String[] args) throws Exception {
   Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
   Connection con = DriverManager
            .getConnection("jdbc:hive://hadoop0:10000/default", "", "");
   Statement stmt = con.createStatement();
   String querySQL="SELECT * FROM default.t1";


    ResultSet res = stmt.executeQuery(querySQL);  


    while (res.next()) {
    System.out.println(res.getInt(1));
    }

    }
    }
8、用戶自定義函數(UDF操作)
    .按下tab鍵,提示是否顯示全部函數,y可以查看全部函數
    顯示所有函數:
    hive> show functions;


    查看函數用法:
    hive> describe function substr;
    hive> describe function pi;     //具體使用,查看某個命令使用方法
        OK
        pi() - returns pi
        Time taken: 0.052 seconds
    求和操作:
    select sum(id) from t1;     //函數求和


9、hive安裝的常見錯誤(包括0.11等版本)
1.hive> show tables;
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask.
java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
導致這個錯誤的原因很多,有必要查看詳細錯誤信息。退出hive,以debug模式啓動hive並將信息顯示到控制檯:
hive -hiveconf hive.root.logger=DEBUG,console發現以上錯誤是由Caused by: 
MetaException(message:Version information not found in metastore. )導致的。
解決方法將hive-site.xml 裏面 hive.metastore.schema.verification 的值改爲 false後,就沒出現錯誤了。
2.[Fatal Error] hive-site.xml:2000:16: The element type "value" must be terminated by the matching 
end-tag "</value>".14/04/14 19:34:36 FATAL conf.Configuration: error parsing conf file: 
org.xml.sax.SAXParseException: The element type "value" must be terminated by the matching 
end-tag "</value>".報錯很明顯hive-site.xml 2000行有錯,查看發現2000行竟是這樣的<value>auth</auth>能
沒錯嗎,將</auth>改爲</value>錯誤解決。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章