Skip to content

Instantly share code, notes, and snippets.

@rajkrrsingh
Last active July 6, 2021 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajkrrsingh/4ab7153ca90969dcad21 to your computer and use it in GitHub Desktop.
Save rajkrrsingh/4ab7153ca90969dcad21 to your computer and use it in GitHub Desktop.
sample java code to connect hive server using thrift client
package com.rajkrrsingh.thrift.client;
import org.apache.hive.service.auth.HiveAuthFactory;
import org.apache.hive.service.auth.PlainSaslHelper;
import org.apache.hive.service.cli.thrift.*;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TTransport;
import javax.security.sasl.SaslException;
import java.util.Iterator;
import java.util.List;
/*
* to make it work add the hive-service and hadoop-client dependencies
* in pom.xml
*/
public class ThriftClient {
public static void main(String[] args) throws TException, SaslException {
TTransport transport = HiveAuthFactory.getSocketTransport("127.0.0.1", 10000,99999);
transport = PlainSaslHelper.getPlainTransport("hive", "hive", transport);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
TCLIService.Client client = new TCLIService.Client(protocol);
transport.open();
TOpenSessionReq openReq = new TOpenSessionReq();
TOpenSessionResp openResp = client.OpenSession(openReq);
TSessionHandle sessHandle = openResp.getSessionHandle();
TExecuteStatementReq execReq = new TExecuteStatementReq(sessHandle, "show tables");
TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
TOperationHandle stmtHandle = execResp.getOperationHandle();
TFetchResultsReq fetchReq = new TFetchResultsReq(stmtHandle, TFetchOrientation.FETCH_FIRST, 100);
TFetchResultsResp resultsResp = client.FetchResults(fetchReq);
List<TColumn> res=resultsResp.getResults().getColumns();
for(TColumn tCol: res){
Iterator<String> it = tCol.getStringVal().getValuesIterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
TCloseOperationReq closeReq = new TCloseOperationReq();
closeReq.setOperationHandle(stmtHandle);
client.CloseOperation(closeReq);
TCloseSessionReq closeConnectionReq = new TCloseSessionReq(sessHandle);
client.CloseSession(closeConnectionReq);
transport.close();
}
}
@bmvsprasad
Copy link

The thrift client is simple and good

Copy link

ghost commented Jul 6, 2021

excuse, how to get hive log? if you have time,can you tell me? please..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment