我在HDFS中有一些数据,我需要使用python访问该数据,任何人都可以告诉我如何使用python从hive访问数据?
Tri*_*eid 12
要安装,您需要这些库:
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Linux,则可能需要在运行上述内容之前单独安装SASL.libsasl2-dev使用apt-get或yum或任何包管理器安装包.对于Windows ,GNU.org上有一些选项.在Mac上,如果您安装了xcode开发工具(xcode-select --install),则应该可以使用SASL
安装后,您可以执行这样的配置单元查询:
from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")
Run Code Online (Sandbox Code Playgroud)
现在您已经拥有了hive连接,您可以选择如何使用它.你可以直接查询:
cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
use_result(result)
Run Code Online (Sandbox Code Playgroud)
...或使用连接来制作Pandas数据帧:
import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)
Run Code Online (Sandbox Code Playgroud)
您可以使用hive库从python访问配置单元,因为您要从hive导入ThriftHive导入配置单元类
在示例下面
import sys
from hive import ThriftHive
from hive.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
transport = TSocket.TSocket('localhost', 10000)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = ThriftHive.Client(protocol)
transport.open()
client.execute("CREATE TABLE r(a STRING, b INT, c DOUBLE)")
client.execute("LOAD TABLE LOCAL INPATH '/path' INTO TABLE r")
client.execute("SELECT * FROM r")
while (1):
row = client.fetchOne()
if (row == None):
break
print row
client.execute("SELECT * FROM r")
print client.fetchAll()
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
Run Code Online (Sandbox Code Playgroud)