网上关于golang操作hive的文章很少, 最近在用, 研究的过程中记一点代码片段.
package my_hive_cli
import (
"..../hive/tcliservice"
"git.apache.org/thrift.git/lib/go/thrift"
)
func NewClient(host string, username string, password string, dbname string) (*tcliservice.TCLIServiceClient, error) {
transport, err := thrift.NewTSocket(host)
if err != nil {
return nil, err
}
if err := transport.Open(); err != nil {
return nil, err
}
protocol := thrift.NewTBinaryProtocolFactoryDefault()
client := tcliservice.NewTCLIServiceClientFactory(transport, protocol)
openSessionReq := tcliservice.NewTOpenSessionReq()
if username != "" {
openSessionReq.Username = &username
openSessionReq.Password = &password
}
openSessionReq.ClientProtocol = tcliservice.TProtocolVersion_HIVE_CLI_SERVICE_PROTOCOL_V5
if dbname != "" {
if openSessionReq.Configuration == nil {
openSessionReq.Configuration = make(map[string]string)
}
openSessionReq.Configuration["use:"] = dbname
}
openSessionResp, err := client.OpenSession(openSessionReq)
if err != nil {
return nil, err
}
sessionHandler := openSessionResp.GetSessionHandle()
exeReq := tcliservice.NewTExecuteStatementReq()
exeReq.SessionHandle = sessionHandler
exeReq.Statement = "SELECT COUNT(1) FROM default.test"
exeResp, err := client.ExecuteStatement(exeReq)
if err != nil {
return nil, err
}
operationHandler := exeResp.GetOperationHandle()
fetchReq := tcliservice.NewTFetchResultsReq()
fetchReq.OperationHandle = operationHandler
fetchReq.Orientation = tcliservice.TFetchOrientation_FETCH_FIRST
fetchReq.MaxRows = 10
fetchResp, err := client.FetchResults(fetchReq)
if err != nil {
return nil, err
}
res := fetchResp.GetResults().GetRows()
for _,r := range res{
row := r.GetColVals()
for _, filed := range row {
if filed.IsSetI64Val() {
println("i64", filed.GetI64Val().GetValue())
}
if filed.IsSetI32Val() {
println("i32", filed.GetI32Val().GetValue())
}
}
}
closeOperationReq := tcliservice.NewTCloseOperationReq()
closeOperationReq.OperationHandle = operationHandler
client.CloseOperation(closeOperationReq)
closeSessionReq := tcliservice.NewTCloseSessionReq()
closeSessionReq.SessionHandle = sessionHandler
client.CloseSession(closeSessionReq)
transport.Close()
return client, nil
}
有疑问加站长微信联系(非本文作者)