hadoop生态--Hive(2)--Hive的使用方式

hive为用户提供了多种使用方式,包括本地客户端交互、将hive做为服务从远程经过客户端交互以及脚本化运行方式(经常使用)java

1、基本运行方式sql

hive是一个单机程序,在安装hive的机器上,执行 hive 启动hive进入hive交互界面(若是没有配置path变量,须要到hive的安装目录下运行bin中hive程序)。shell

进入交互界面后就能够执行各类对库、表的增删改查数据库

2、将hive启动为服务apache

启动hive服务,监听10000端口,就不须要必须在安装hive的服务器上进行,能够在任意能够与hive服务通讯的机器上启动hive客户端—beeline与hive服务器交互。服务器

hive在$hive_home/bin下提供了hiveserver2程序用于启动hive服务,提供beeline程序做为客户端。maven

step1.启动hive服务oop

在安装hive服务的机器上执行 hiveserver2 就能够启动服务(若是没有配置环境变量直接到安装目录下执行),通常会在后台静默运行。ui

nohup hiveserver2 1>/dev/null 2>&1 &

step2.在能够与hi v额服务器通讯的机器上执行 beeline 进入beeline的交互界面spa

!connect jdbc:hive2://hdp-01:1000

输入HDFS用户名、密码。这样完成链接,能够经过交互在hive服务器上执行。

step3.交互执行操做

#关闭链接 !close #退出beeline,服务会继续运行,只能到hive服务器关闭 !quit

3、脚本化运行(经常使用)

使用一次性命令的方式来执行给定的hql语句。

方式一、hive -e “要执行语句”

这样的方式,能够不须要进入hive交互式界面,直接使用shell命令输入 hive -e "select * from student" 来进行查询等操做。

在这样的基础上就能够写一个.sh脚原本写入多条hive -e命令,而后执行sh文件

方式二、hive -f test.hql

还能够把hql语句直接写到脚本中(不须要写hive -e),把文件保存为 .hql 格式,经过执行 hive -f test.hql 来执行hql语句。

4、经过JDBC访问hive

0、导包

maven官方查询hive依赖

 

<dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-jdbc</artifactId>
      <version>2.1.0</version>
    </dependency>

 

一、注册、链接、查询

 

package com.jing.hadoop; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * 使用jdbc方式链接到hive数据仓库,hive须要开启hive server2服务 * */
public class App { public static void main( String[] args ) throws Exception{ //加载hive jdbc驱动,并注册到DriverManager
        Class.forName("org.apache.hive.jdbc.HiveDriver"); //得到数据库链接
        Connection conn = DriverManager.getConnection("jdbc:hive2//192.168.1.236:10000/mydb2"); //         Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select id, name, age from t"); while(rs.next()){ System.out.println(rs.getInt((1)) + "," + rs.getString(2)); } rs.close(); st.close(); conn.close(); } }

 

 

 

 

 


hive建库建表导入数据

一、建库、建表(以基本运行方式为例)

show databases; create database hive_test; create table student(id int, name string);

 这样操做以后会在hdfs上建立目录,,,/usr/hive/warehouse

把文件放到student目录下,在hive上的表现就是表内有数据了。表内各字段的值就是文件内一行记录被分割以后的值。

注意:hive切字段时默认使用的分隔符是\001,因此建立的文件中,字段之间使用^A分割(我在使用的时候很差使,未查到问题出在哪里)。支持自定义用于分割的字符。

create table t_order(id string,create_time string,amount float,uid string) row format delimited fields terminated by ',';

二、根据模板表建立表

建立的表不包含数据

create table table-name like table-2-name

建立的表包含数据:

create table 
as
select * from table-2

 二、导入数据

1)手动hdfs命令,将文件放入表目录
2)hive交互中,hive命令导入
将本地数据导入 
load data local inpath ‘/local/path’ into table t_name partition(singal='singal_value');

(注意这里的local是对hive服务器而言的)

load data inpath ‘/hdfs/path’ into table t_name partition(singal='singal_value');

从本地导入和hdfs导入的区别:本地文件导入是复制,hdfs导入是移动

相关文章
相关标签/搜索