Python
PyHive
登录后可跨设备保存划线和私人笔记登录
PyHive 是一个用于 Hive 的 Python DB-API 和 SQLAlchemy 接口集合。PyHive 可以以 HiveServer2 身份通过 thrift 协议连接到 Kyuubi 服务器。
环境要求
PyHive 支持 Python 2.7 / Python 3。通过 pip 安装 PyHive 以使用 Hive 接口。
pip install 'pyhive[hive]'用法
使用 Kyuubi 服务的主机地址和 Thrift 协议端口进行连接。
如需了解用法和特性的更多信息,例如 DB-API 异步获取、在 SQLAlchemy 中使用等,请参阅项目主页。
DB-API
from pyhive import hive
cursor = hive.connect(host=kyuubi_host,port=10009).cursor()
cursor.execute('SELECT * FROM my_awesome_data LIMIT 10')
print(cursor.fetchone())
print(cursor.fetchall())在 Pandas 中使用 PyHive
PyHive 提供了一种便捷的方式来建立兼容 SQLAlchemy 的连接,可配合 Pandas DataFrame 使用,通过 pandas.read_sql 执行 SQL 并读取数据。
from pyhive import hive
import pandas as pd
# open connection
conn = hive.Connection(host=kyuubi_host,port=10009)
# query the table to a new dataframe
dataframe = pd.read_sql("SELECT id, name FROM test.example_table", conn)认证
如果连接时提供了密码,请确保 auth 参数设置为 CUSTOM 或 LDAP。
# open connection
conn = hive.Connection(host=kyuubi_host, port=10009,
username='user', password='password', auth='CUSTOM')使用 Kerberos 连接 Kyuubi。
kerberos_service_name 必须是启动 Kyuubi 服务端的服务名称,通常是 kyuubi.kinit.principal 中第一个斜杠前的前缀。
请注意,PyHive 不支持传入 principal,它会将 principal 的一部分与 kerberos_service_name 和 kyuubi_host 拼接起来。
# open connection
conn = hive.Connection(host=kyuubi_host, port=10009, auth="KERBEROS", kerberos_service_name="kyuubi")如果你遇到以下错误,则需要安装相关依赖包。
thrift.transport.TTransport.TTransportException: Could not start SASL: b'Error in sasl_client_start (-4) SASL(-4): no mechanism available: No worthy mechs found'yum install -y cyrus-sasl-plain cyrus-sasl-devel cyrus-sasl-gssapi cyrus-sasl-md5请注意,PyHive 不支持基于 ZooKeeper HA 的连接方式,你可以通过 Kazoo 连接到 ZooKeeper 以获取服务地址。
代码参考 https://stackoverflow.com/a/73326589
from pyhive import hive
import random
from kazoo.client import KazooClient
zk = KazooClient(hosts='kyuubi1.xx.com:2181,kyuubi2.xx.com:2181,kyuubi3.xx.com:2181', read_only=True)
zk.start()
servers = [kyuubi_server.split(';')[0].split('=')[1].split(':')
for kyuubi_server
in zk.get_children(path='kyuubi')]
kyuubi_host, kyuubi_port = random.choice(servers)
zk.stop()
print(kyuubi_host, kyuubi_port)
conn = hive.Connection(host=kyuubi_host, port=kyuubi_port, auth="KERBEROS", kerberos_service_name="kyuubi")评论
登录后参与评论
正在加载评论…
KnowForge