前言
公司的测试和生产环境中尚未提供基于Hive的客户端。若希望尝试操作Hive表,目前一个可行的方案是使用Python语言,通过借助pyhive库,您可以对Hive表进行各种操作。以下是一些示例记录供您参考。
一、pyhive是什么?
PyHive是一个Python库,用于与Apache Hive进行交互和查询。Apache Hive是建立在Hadoop平台上的数据仓库工具,旨在方便地执行SQL类型的查询以分析大型数据集。PyHive库允许Python开发人员通过编程语言来访问和操作Hive数据库,从而进行数据查询、分析和处理。
通过PyHive,可以使用Python编写Hive查询和命令,并从Python应用程序中直接访问和操作Hive中存储的数据。PyHive提供了与Hive数据库交互所需的API和功能,使得在Python环境中进行大规模数据处理变得更加简单和高效。
二、本地安装 pyhive库
1. 安装 pip 包管理工具
在Python环境中,通常会同时安装有pip和pip3这两个包管理工具,它们的主要区别在于所针对的Python版本。
pip:pip是用于Python 2.x版本的包管理工具。在Python 2.x环境下,pip通常是默认的包管理工具,用于安装、升级和管理Python包和依赖项。
pip3:pip3则是专为Python 3.x版本设计的包管理工具。在Python 3.x环境中,pip3用于安装、升级和管理Python 3.x的包和依赖项。需要注意的是,在某些情况下,pip3也可以用来代替pip,以确保在Python 2.x和Python 3.x环境中都能使用相同的包管理工具。
因此如果需要在Python 3环境下安装包时,应优先选择使用pip3来安装,以确保Python 3.x环境中的包管理工具正确安装和管理依赖项。如果您同时使用Python 2和Python 3环境,则需要注意使用不同的pip版本以避免混淆和冲突。
在 MacBook 上安装 pip 工具,可以按照以下步骤进行:
1. 安装 Homebrew(如果尚未安装)
Homebrew 是一个包管理工具,可以用来方便地安装和管理 macOS 上的软件包。
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2. 安装 Python(包括 pip)
使用 Homebrew 安装 Python,pip 通常会随 Python 一起安装。
brew install python
安装完成后,你可以检查 python3
和 pip3
是否已经安装:
python3 --version
pip3 --version
3. 安装或升级 pip
如果你已经有 Python 安装,但没有 pip 或需要升级 pip,可以使用以下命令:
python3 -m ensurepip --upgrade
或者,如果你已经有 pip,可以通过以下命令升级它:
pip3 install --upgrade pip
4. 使用 pip 安装包
确认 pip 安装成功后,你可以使用 pip 安装 Python 包。例如,安装 requests
包(做个测试):
pip3 install requests
(myenv) ➜ ~ pip3 install requests
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting requests
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f9/9b/335f9764261e915ed497fcdeb11df5dfd6f7bf257d4a6a2a686d80da4d54/requests-2.32.3-py3-none-any.whl (64 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 64.9/64.9 kB 1.6 MB/s eta 0:00:00
Collecting charset-normalizer<4,>=2 (from requests)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/2e/7d/2259318c202f3d17f3fe6438149b3b9e706d1070fe3fcbb28049730bb25c/charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_x86_64.whl (122 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 122.2/122.2 kB 4.1 MB/s eta 0:00:00
Collecting idna<4,>=2.5 (from requests)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e5/3e/741d8c82801c347547f8a2a06aa57dbb1992be9e948df2ea0eda2c8b79e8/idna-3.7-py3-none-any.whl (66 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 66.8/66.8 kB 2.1 MB/s eta 0:00:00
Collecting urllib3<3,>=1.21.1 (from requests)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/a2/73/a68704750a7679d0b6d3ad7aa8d4da8e14e151ae82e6fee774e6e0d05ec8/urllib3-2.2.1-py3-none-any.whl (121 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 121.1/121.1 kB 4.0 MB/s eta 0:00:00
Collecting certifi>=2017.4.17 (from requests)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/5b/11/1e78951465b4a225519b8c3ad29769c49e0d8d157a070f681d5b6d64737f/certifi-2024.6.2-py3-none-any.whl (164 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 164.4/164.4 kB 4.1 MB/s eta 0:00:00
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2024.6.2 charset-normalizer-3.3.2 idna-3.7 requests-2.32.3 urllib3-2.2.1
额外步骤:安装虚拟环境(可选)
使用虚拟环境可以帮助你管理项目依赖:
pip3 install virtualenv
创建一个新的虚拟环境:
python3 -m venv myenv
激活虚拟环境:
source myenv/bin/activate
退出虚拟环境:
deactivate
如何安装的速度太慢可以考虑换下国内的镜像:
常见的国内镜像源
以下是几个常见的国内 PyPI 镜像源:
清华大学: https://pypi.tuna.tsinghua.edu.cn/simple
阿里云: https://mirrors.aliyun.com/pypi/simple/
豆瓣(douban): https://pypi.douban.com/simple/
中国科学技术大学: https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学: https://pypi.hustunique.com/
2. 实操演示
代码如下(示例):
# 新建虚拟环境
➜ ~ python3 -m venv myenv
# 激活环境
➜ ~ source myenv/bin/activate
(myenv) ➜ ~ python -m pip install pyhive
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting pyhive
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f6/ec/5c658b3a4d99a6d9145030cc8e003c3f7efc668d866e88544812ab0af310/PyHive-0.7.0.tar.gz (46 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 46.5/46.5 kB 652.1 kB/s eta 0:00:00
Installing build dependencies ... done
Getting requirements to build wheel ... done
Installing backend dependencies ... done
Preparing metadata (pyproject.toml) ... done
Collecting future (from pyhive)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/da/71/ae30dadffc90b9006d77af76b393cb9dfbfc9629f339fc1574a1c52e6806/future-1.0.0-py3-none-any.whl (491 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 491.3/491.3 kB 3.1 MB/s eta 0:00:00
Collecting python-dateutil (from pyhive)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 229.9/229.9 kB 5.7 MB/s eta 0:00:00
Collecting six>=1.5 (from python-dateutil->pyhive)
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d9/5a/e7c31adbe875f2abbb91bd84cf2dc52d792b5a01506781dbcf25c91daf11/six-1.16.0-py2.py3-none-any.whl (11 kB)
Building wheels for collected packages: pyhive
Building wheel for pyhive (pyproject.toml) ... done
Created wheel for pyhive: filename=PyHive-0.7.0-py3-none-any.whl size=53872 sha256=da53a804b81ecb864a3cc38acb060e3b17bd93cf9c7d914ebdccdbd999964302
Stored in directory: /Users/mac/Library/Caches/pip/wheels/99/bf/03/0562e50cb60a3bcb0e09602d7060ea2c6da7039f99bda3ec86
Successfully built pyhive
Installing collected packages: six, future, python-dateutil, pyhive
Successfully installed future-1.0.0 pyhive-0.7.0 python-dateutil-2.9.0.post0 six-1.16.0
# 进入环境测试导入包无错误
➜ ~ source myenv/bin/activate
(myenv) ➜ ~ python
Python 3.12.3 (main, Apr 9 2024, 08:09:14) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyhive import hive
>>>
# 注意,如果还是报错可能还需要安装其他包(按照要求安装即可)
pip install pyhive
pip install thrift
pip install sasl
pip install thrift_sasl
3. 测试连接hive示例
3.1 hive连接 jdbc 命令行
(myenv) ➜ hive bin/beeline -u jdbc:hive2://localhost:10000 -n root -p root
Connected to: Apache Hive (version 3.1.3)
Driver: Hive JDBC (version 3.1.3)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 3.1.3 by Apache Hive
0: jdbc:hive2://localhost:10000> show databases;
INFO : Compiling command(queryId=mac_20240608144604_4395d68b-785d-4808-8c09-1732ad816350): show databases
INFO : Concurrency mode is disabled, not creating a lock manager
INFO : Semantic Analysis Completed (retrial = false)
INFO : Returning Hive schema: Schema(fieldSchemas:[FieldSchema(name:database_name, type:string, comment:from deserializer)], properties:null)
INFO : Completed compiling command(queryId=mac_20240608144604_4395d68b-785d-4808-8c09-1732ad816350); Time taken: 0.748 seconds
INFO : Concurrency mode is disabled, not creating a lock manager
INFO : Executing command(queryId=mac_20240608144604_4395d68b-785d-4808-8c09-1732ad816350): show databases
INFO : Starting task [Stage-0:DDL] in serial mode
INFO : Completed executing command(queryId=mac_20240608144604_4395d68b-785d-4808-8c09-1732ad816350); Time taken: 0.037 seconds
INFO : OK
INFO : Concurrency mode is disabled, not creating a lock manager
+----------------+
| database_name |
+----------------+
| default |
| test |
| tmp |
+----------------+
3 rows selected (1.113 seconds)
0: jdbc:hive2://localhost:10000>
0: jdbc:hive2://localhost:10000> select * from test.login_data limit 3;
+----------------------+------------------------+------------------+----------------+
| login_data.logtime | login_data.account_id | login_data.ip | login_data.dt |
+----------------------+------------------------+------------------+----------------+
| 2019-07-15 00:00:00 | 102325 | 223.116.97.23 | 2019-07-15 |
| 2019-07-15 00:00:00 | 221977 | 223.104.247.162 | 2019-07-15 |
| 2019-07-15 00:00:00 | 223764 | 59.32.248.102 | 2019-07-15 |
+----------------------+------------------------+------------------+----------------+
3 rows selected (1.487 seconds)
3.2 pyhive连接获取数据示例
(myenv) ➜ ~ python
Python 3.12.3 (main, Apr 9 2024, 08:09:14) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyhive import hive
>>> conn = hive.Connection(host="localhost", port=10000, username="root")
>>> cursor = conn.cursor()
>>> cursor.execute('select * from test.login_data limit 3')
>>> for row in cursor.fetchall():
... print(row)
...
('2019-07-15 00:00:00', 102325, '223.116.97.23', '2019-07-15')
('2019-07-15 00:00:00', 221977, '223.104.247.162', '2019-07-15')
('2019-07-15 00:00:00', 223764, '59.32.248.102', '2019-07-15')
>>> cursor.close()
>>> conn.close()
完整示例:
from pyhive import hive
import logging
# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
# 配置 Hive 连接参数
host = 'localhost'
port = 10000
username = 'root'
database = 'test'
# 创建连接
conn = hive.Connection(host=host, port=port, username=username, database=database)
# 创建游标
cursor = conn.cursor()
# 执行查询
query = 'select * from test.login_data limit 3'
cursor.execute(query)
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
except Exception as e:
logger.error("Error occurred while connecting to Hive or executing query", exc_info=True)
finally:
# 确保游标和连接在异常情况下也能正确关闭
try:
if cursor:
cursor.close()
except Exception as e:
logger.error("Error occurred while closing cursor", exc_info=True)
try:
if conn:
conn.close()
except Exception as e:
logger.error("Error occurred while closing connection", exc_info=True)
运行结果:
(myenv) ➜ tmp python test.py
INFO:pyhive.hive:USE `test`
INFO:pyhive.hive:select * from test.login_data limit 3
('2019-07-15 00:00:00', 102325, '223.116.97.23', '2019-07-15')
('2019-07-15 00:00:00', 221977, '223.104.247.162', '2019-07-15')
('2019-07-15 00:00:00', 223764, '59.32.248.102', '2019-07-15')
未解决问题
使用 Pycharm开发的时候提示如下报错:
这个应该是没有应用到我虚拟 myenv环境导致的,尝试新建一个新的解释器但是未成功,有么有知道怎么做的欢迎和我讨论。
参考
https://www.cnblogs.com/SunshineKimi/p/12969751.html