這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
網上關於golang操作hive的文章很少, 最近在用, 研究的過程中記一點程式碼片段.
package my_hive_cliimport ("..../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 = &usernameopenSessionReq.Password = &password}openSessionReq.ClientProtocol = tcliservice.TProtocolVersion_HIVE_CLI_SERVICE_PROTOCOL_V5if 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 = sessionHandlerexeReq.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 = operationHandlerfetchReq.Orientation = tcliservice.TFetchOrientation_FETCH_FIRSTfetchReq.MaxRows = 10fetchResp, 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 = operationHandlerclient.CloseOperation(closeOperationReq)closeSessionReq := tcliservice.NewTCloseSessionReq()closeSessionReq.SessionHandle = sessionHandlerclient.CloseSession(closeSessionReq)transport.Close()return client, nil}