Apache Hive命令行客户端beeline使用介绍

Apache Hive自带的命令行客户端(Beeline),主要作用是通过 JDBC 连接 HiveServer2,然后执行 Hive SQL。

Beeline = HiveServer2 的命令行客户端


1. 它和 hive 命令有什么区别?

传统 Hive 中常见:

1
hive

它通常是直接启动 Hive CLI,而:

1
/opt/hive/bin/beeline

是通过 JDBC → HiveServer2 → Hadoop/Hive 的方式执行 SQL。

beeline架构

1
2
3
4
5
6
7
8
9
                    JDBC
Beeline ─────────────────────────> HiveServer2
│ │
│ │
│ ▼
│ Hive
│ │
│ ▼
│ HDFS / Metastore

现代Hive 环境一般更推荐 Beeline + HiveServer2


2. 基本用法

2.1交互模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/opt/hive/bin/beeline

# 非认证模式
!connect jdbc:hive2://localhost:10000
show databases;

/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default'

jdbc:hive2://localhost:10000/default
│ │
│ └── 数据库
└───────────── HiveServer2 端口
# 如果HiveServer2在其他机器
/opt/hive/bin/beeline \
-u 'jdbc:hive2://192.168.1.100:10000/default'

# 用户密码认证
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-n hive \
-p password

2.2非交互模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 非交互执行SQL
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-e 'show databases;'

/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-e 'select count(*) from test.user;'

/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-e '
use test;
show tables;
select count(*) from user;
'

# 执行sql文件
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-f /opt/sql/test.sql

# 输出结果保存到文件
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-e 'select * from test.user;' \
> result.txt

# 设置输出格式csv2
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
--outputformat=csv2 \
-e 'select * from test.user;' \
> result.csv

常见输出格式包括:

1
2
3
4
--outputformat=table
--outputformat=csv2
--outputformat=tsv2
--outputformat=dsv

3. beeline常见参数

可以查看:

1
/opt/hive/bin/beeline --help

常见参数:

参数 作用
-u JDBC URL
-n 用户名
-p 密码
-e 直接执行SQL
-f 执行SQL文件
--outputformat 指定输出格式
--silent=true 减少日志输出
--showHeader=false 不显示字段名
--verbose=true 显示详细信息

例如:

1
2
3
4
5
6
/opt/hive/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
--silent=true \
--showHeader=false \
--outputformat=csv2 \
-e 'select count(*) from test.user;'

-e-f 的本质区别

1
2
beeline -u 'jdbc:hive2://localhost:10000' \
-e 'select count(*) from test.user;'

适合:

  • 临时查询
  • Shell 脚本
  • 简单 SQL

1
2
beeline -u 'jdbc:hive2://localhost:10000' \
-f daily.sql

适合:

  • 大量 SQL
  • ETL
  • 调度任务
  • 数据仓库生产任务

脚本中的典型写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

HIVE_HOME=/opt/hive

$HIVE_HOME/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
--outputformat=csv2 \
-e "
use test;

insert into table user_result
select
id,
name
from user
where dt='2026-09-03';
"

也可以:

1
2
3
$HIVE_HOME/bin/beeline \
-u 'jdbc:hive2://localhost:10000/default' \
-f /opt/sql/user_result.sql