java連接hive
❶ 如何使用kettle連接hive和hive2
連接hive的方法:
進入hive所在的伺服器,輸入:hive --service hiveserver(目的:啟動thrift)
打開kettle配置連接界面,輸入hive所在伺服器的ip、所需要的hive庫、埠號(thrift默認埠為:10000)
測試連接,即可
連接hive2的方法:
Error connecting to database [Hive] : org.pentaho.di.core.exception.KettleDatabaseException:
Error occured while trying to connect to the database
Error connecting to database: (using class org.apache.hadoop.hive.jdbc.HiveDriver)
Unable to load Hive Server 2 JDBC driver for the currently active Hadoop configuration
org.pentaho.di.core.exception.KettleDatabaseException:
Error occured while trying to connect to the database
Error connecting to database: (using class org.apache.hadoop.hive.jdbc.HiveDriver)
Unable to load Hive Server 2 JDBC driver for the currently active Hadoop configuration
at org.pentaho.di.core.database.Database.normalConnect(Database.java:428)
at org.pentaho.di.core.database.Database.connect(Database.java:361)
at org.pentaho.di.core.database.Database.connect(Database.java:314)
at org.pentaho.di.core.database.Database.connect(Database.java:302)
at org.pentaho.di.core.database.DatabaseFactory.getConnectionTestReport(DatabaseFactory.java:80)
at org.pentaho.di.core.database.DatabaseMeta.testConnection(DatabaseMeta.java:2685)
at org.pentaho.di.ui.core.database.dialog.DatabaseDialog.test(DatabaseDialog.java:109)
at org.pentaho.di.ui.core.database.wizard.CreateDatabaseWizardPage2.test(CreateDatabaseWizardPage2.java:157)
at org.pentaho.di.ui.core.database.wizard.CreateDatabaseWizardPage2$3.widgetSelected(CreateDatabaseWizardPage2.java:147)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:820)
at org.eclipse.jface.window.Window.open(Window.java:796)
at org.pentaho.di.ui.core.database.wizard.CreateDatabaseWizard.createAndRunDatabaseWizard(CreateDatabaseWizard.java:111)
at org.pentaho.di.ui.spoon.Spoon.createDatabaseWizard(Spoon.java:7457)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.pentaho.ui.xul.impl.AbstractXulDomContainer.invoke(AbstractXulDomContainer.java:313)
at org.pentaho.ui.xul.impl.AbstractXulComponent.invoke(AbstractXulComponent.java:157)
at org.pentaho.ui.xul.impl.AbstractXulComponent.invoke(AbstractXulComponent.java:141)
at org.pentaho.ui.xul.jface.tags.JfaceMenuitem.access$100(JfaceMenuitem.java:43)
at org.pentaho.ui.xul.jface.tags.JfaceMenuitem$1.run(JfaceMenuitem.java:106)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:545)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:490)
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:402)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.pentaho.di.ui.spoon.Spoon.readAndDispatch(Spoon.java:1297)
at org.pentaho.di.ui.spoon.Spoon.waitForDispose(Spoon.java:7801)
at org.pentaho.di.ui.spoon.Spoon.start(Spoon.java:9130)
at org.pentaho.di.ui.spoon.Spoon.main(Spoon.java:638)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.pentaho.commons.launcher.Launcher.main(Launcher.java:151)
Caused by: org.pentaho.di.core.exception.KettleDatabaseException:
Error connecting to database: (using class org.apache.hadoop.hive.jdbc.HiveDriver)
Unable to load Hive Server 2 JDBC driver for the currently active Hadoop configuration
at org.pentaho.di.core.database.Database.connectUsingClass(Database.java:573)
at org.pentaho.di.core.database.Database.normalConnect(Database.java:410)
... 43 more
Caused by: java.sql.SQLException: Unable to load Hive Server 2 JDBC driver for the currently active Hadoop configuration
at org.apache.hive.jdbc.HiveDriver.getActiveDriver(HiveDriver.java:107)
at org.apache.hive.jdbc.HiveDriver.callWithActiveDriver(HiveDriver.java:121)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:132)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.pentaho.di.core.database.Database.connectUsingClass(Database.java:555)
... 44 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.hive.jdbc.HiveDriver.getActiveDriver(HiveDriver.java:105)
... 49 more
Caused by: java.lang.RuntimeException: Unable to load JDBC driver of type: hive2
at org.pentaho.hadoop.shim.common.CommonHadoopShim.getJdbcDriver(CommonHadoopShim.java:108)
... 54 more
Caused by: java.lang.Exception: JDBC driver of type 'hive2' not supported
at org.pentaho.hadoop.shim.common.CommonHadoopShim.getJdbcDriver(CommonHadoopShim.java:104)
... 54 more
上述報錯的解決方法如下:
1.找到%KETTLE_HOME%/plugins/pehtaho-big-data-plugin/plugin.properties文件
2.修改plugin.properties文件中的值:active.hadoop.configuration=hdp13
3.修改後重啟kettle
4.配置完成後,即可連接上對應的庫
如果要使用hadoop-20,則需要添加如下jar包:
hadoop-core-1.2.1.jar
hive-common-0.13.0.jar
hive-jdbc-0.13.0.jar
hive-service-0.13.0.jar
libthrift-0.9.1.jar
slf4j-api-1.7.5.jar
httpclient-4.2.5.jar
httpcore-4.2.5.jar
總結:使用hive2的好處,優化了連接、增加安全性、並行度
❷ 如何生成hive的建表語句
Java連接Hive
利用jdbc連接到hive,使用Java程序寫一個循環。
先獲取全部表,然後show create table每個表。
沒能嘗試成功,一直連接不上:
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveTestCase {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args)
throws SQLException {
try {
Class.forName(driverNa
❸ java怎麼創建hivemetastoreclient
下面就來解釋下系統是如何生成meta client的!
先來看幾段代碼!
publicvoidcreateDatabase(Databasedb,booleanifNotExist)throwsAlreadyExistsException,HiveException{
try{
getMSC().createDatabase(db);
}catch(AlreadyExistsExceptione){
if(!ifNotExist){
throwe;
}
}catch(Exceptione){
thrownewHiveException(e);
}
}
=========
privateIMetaStoreClientgetMSC()throwsMetaException{
if(metaStoreClient==null){
metaStoreClient=createMetaStoreClient();
}
returnmetaStoreClient;
}
=========
()throwsMetaException{
HiveMetaHookLoaderhookLoader=newHiveMetaHookLoader(){
publicHiveMetaHookgetHook(org.apache.hadoop.hive.metastore.api.Tabletbl)throwsMetaException{
try{
if(tbl==null){
returnnull;
}
=HiveUtils.getStorageHandler(conf,
tbl.getParameters().get(META_TABLE_STORAGE));
if(storageHandler==null){
returnnull;
}
returnstorageHandler.getMetaHook();
}catch(HiveExceptionex){
LOG.error(StringUtils.stringifyException(ex));
thrownewMetaException("Failedtoloadstoragehandler:"+ex.getMessage());
}
}
};
returnnewHiveMetaStoreClient(conf,hookLoader);
}
=========
publicHiveMetaStoreClient(HiveConfconf,HiveMetaHookLoaderhookLoader)
throwsMetaException{
this.hookLoader=hookLoader;
if(conf==null){
conf=newHiveConf(HiveMetaStoreClient.class);
}
this.conf=conf;
localMetaStore=conf.getBoolVar(ConfVars.METASTORE_MODE);
if(localMetaStore){
//
//throughthenetwork
client=newHiveMetaStore.HMSHandler("hiveclient",conf);
isConnected=true;
return;
}
//getthenumberretries
retries=HiveConf.getIntVar(conf,HiveConf.ConfVars.METASTORETHRIFTRETRIES);
retryDelaySeconds=conf.getIntVar(ConfVars.METASTORE_CLIENT_CONNECT_RETRY_DELAY);
//
if(conf.getVar(HiveConf.ConfVars.METASTOREURIS)!=null){
StringmetastoreUrisString[]=conf.getVar(
HiveConf.ConfVars.METASTOREURIS).split(",");
metastoreUris=newURI[metastoreUrisString.length];
try{
inti=0;
for(Strings:metastoreUrisString){
URItmpUri=newURI(s);
if(tmpUri.getScheme()==null){
("URI:"+s
+"doesnothaveascheme");
}
metastoreUris[i++]=tmpUri;
}
}catch(IllegalArgumentExceptione){
throw(e);
}catch(Exceptione){
MetaStoreUtils.logAndThrowMetaException(e);
}
}elseif(conf.getVar(HiveConf.ConfVars.METASTOREDIRECTORY)!=null){
metastoreUris=newURI[1];
try{
metastoreUris[0]=newURI(conf
.getVar(HiveConf.ConfVars.METASTOREDIRECTORY));
}catch(URISyntaxExceptione){
MetaStoreUtils.logAndThrowMetaException(e);
}
}else{
LOG.error("NOTgettingurisfromconf");
thrownewMetaException("");
}
//finallyopenthestore
open();
}
下面要認真分析下上面的這段代碼,因為關聯到一些參數的配置,對於理解生產環境的部署參數有幫助!先看下面這段代碼
localMetaStore=conf.getBoolVar(ConfVars.METASTORE_MODE);
if(localMetaStore){
//
//connecting
//throughthenetwork
client=newHiveMetaStore.HMSHandler("hiveclient",conf);
isConnected=true;
return;
}
PS:ConfVars.METASTORE_MODE---METASTORE_MODE("hive.metastore.local",true),
❹ hive 需要寫java代碼嗎
如果你的項目是java項目的話,就需要使用hive提供的java api,如下代碼:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* Hive的JavaApi
*
* 啟動hive的遠程服務介面命令行執行:hive --service hiveserver >/dev/null 2>/dev/null &
*
* @author 吖大哥
*
*/
public class HiveJdbcCli {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
private static String url = "jdbc:hive://hadoop3:10000/default";
private static String user = "hive";
private static String password = "mysql";
private static String sql = "";
private static ResultSet res;
private static final Logger log = Logger.getLogger(HiveJdbcCli.class);
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
conn = getConn();
stmt = conn.createStatement();
// 第一步:存在就先刪除
String tableName = dropTable(stmt);
// 第二步:不存在就創建
createTable(stmt, tableName);
// 第三步:查看創建的表
showTables(stmt, tableName);
// 執行describe table操作
describeTables(stmt, tableName);
// 執行load data into table操作
loadData(stmt, tableName);
// 執行 select * query 操作
selectData(stmt, tableName);
// 執行 regular hive query 統計操作
countData(stmt, tableName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
log.error(driverName + " not found!", e);
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
log.error("Connection error!", e);
System.exit(1);
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void countData(Statement stmt, String tableName)
throws SQLException {
sql = "select count(1) from " + tableName;
System.out.println("Running:" + sql);
res = stmt.executeQuery(sql);
System.out.println("執行「regular hive query」運行結果:");
while (res.next()) {
System.out.println("count ------>" + res.getString(1));
}
}
private static void selectData(Statement stmt, String tableName)
throws SQLException {
sql = "select * from " + tableName;
System.out.println("Running:" + sql);
res = stmt.executeQuery(sql);
System.out.println("執行 select * query 運行結果:");
while (res.next()) {
System.out.println(res.getInt(1) + "\t" + res.getString(2));
}
}
private static void loadData(Statement stmt, String tableName)
throws SQLException {
String filepath = "/home/hadoop01/data";
sql = "load data local inpath '" + filepath + "' into table "
+ tableName;
System.out.println("Running:" + sql);
res = stmt.executeQuery(sql);
}
private static void describeTables(Statement stmt, String tableName)
throws SQLException {
sql = "describe " + tableName;
System.out.println("Running:" + sql);
res = stmt.executeQuery(sql);
System.out.println("執行 describe table 運行結果:");
while (res.next()) {
System.out.println(res.getString(1) + "\t" + res.getString(2));
}
}
private static void showTables(Statement stmt, String tableName)
throws SQLException {
sql = "show tables '" + tableName + "'";
System.out.println("Running:" + sql);
res = stmt.executeQuery(sql);
System.out.println("執行 show tables 運行結果:");
if (res.next()) {
System.out.println(res.getString(1));
}
}
private static void createTable(Statement stmt, String tableName)
throws SQLException {
sql = "create table "
+ tableName
+ " (key int, value string) row format delimited fields terminated by '\t'";
stmt.executeQuery(sql);
}
private static String dropTable(Statement stmt) throws SQLException {
// 創建的表名
String tableName = "testHive";
sql = "drop table " + tableName;
stmt.executeQuery(sql);
return tableName;
}
private static Connection getConn() throws ClassNotFoundException,
SQLException {
Class.forName(driverName);
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
}
❺ Hive入門概述
1.1 什麼是Hive
Hive:由Facebook開源用於解決海量結構化日誌的數據統計。
Hive是基於Hadoop的一個數據倉庫工具,可以將結構化的數據文件映射為一張表,並提供類SQL查詢功能。本質是:將HQL轉化成MapRece程序
Hive處理的數據存儲在HDFS
Hive分析數據底層的實現是MapRece
執行程序運行在Yarn上
1.2 Hive的優缺點
1.2.1 優點
操作介面採用類SQL語法,提供快速開發的能力(簡單、容易上手)。
避免了去寫MapRece,減少開發人員的學習成本。
Hive的執行延遲比較高,因此Hive常用於數據分析,對實時性要求不高的場合。
Hive優勢在於處理大數據,對於處理小數據沒有優勢,因為Hive的執行延遲比較高。
Hive支持用戶自定義函數,用戶可以根據自己的需求來實現自己的函數。
1.2.2 缺點
1.Hive的HQL表達能力有限
(1)迭代式演算法無法表達
(2)數據挖掘方面不擅長
2.Hive的效率比較低
(1)Hive自動生成的MapRece作業,通常情況下不夠智能化
(2)Hive調優比較困難,粒度較粗
1.3 Hive架構原理
1.用戶介面:Client
CLI(hive shell)、JDBC/ODBC(java訪問hive)、WEBUI(瀏覽器訪問hive)
2.元數據:Metastore
元數據包括:表名、表所屬的資料庫(默認是default)、表的擁有者、列/分區欄位、表的類型(是否是外部表)、表的數據所在目錄等;
默認存儲在自帶的derby資料庫中,推薦使用MySQL替代derby存儲Metastore
3.Hadoop
使用HDFS進行存儲,使用MapRece進行計算。
4.驅動器:Driver
(1)解析器(SQL Parser):將SQL字元串轉換成抽象語法樹AST,這一步一般都用第三方工具庫完成,比如antlr;對AST進行語法分析,比如表是否存在、欄位是否存在、SQL語義是否有誤。
(2)編譯器(Physical Plan):將AST編譯生成邏輯執行計劃。
(3)優化器(Query Optimizer):對邏輯執行計劃進行優化。
(4)執行器(Execution):把邏輯執行計劃轉換成可以運行的物理計劃。對於Hive來說,就是MR/Spark。
Hive通過給用戶提供的一系列交互介面,接收到用戶的指令(SQL),使用自己的Driver,結合元數據(MetaStore),將這些指令翻譯成MapRece,提交到Hadoop中執行,最後,將執行返回的結果輸出到用戶交互介面。
1.4 Hive和資料庫比較
由於 Hive 採用了類似SQL 的查詢語言 HQL(Hive Query Language),因此很容易將 Hive 理解為資料庫。其實從結構上來看,Hive 和資料庫除了擁有類似的查詢語言,再無類似之處。本文將從多個方面來闡述 Hive 和資料庫的差異。資料庫可以用在 Online 的應用中,但是Hive 是為數據倉庫而設計的,清楚這一點,有助於從應用角度理解 Hive 的特性。
1.4.1 查詢語言
由於SQL被廣泛的應用在數據倉庫中,因此,專門針對Hive的特性設計了類SQL的查詢語言HQL。熟悉SQL開發的開發者可以很方便的使用Hive進行開發。
1.4.2 數據存儲位置
Hive 是建立在 Hadoop 之上的,所有 Hive 的數據都是存儲在 HDFS 中的。而資料庫則可以將數據保存在塊設備或者本地文件系統中。
1.4.3 數據更新
由於Hive是針對數據倉庫應用設計的,而數據倉庫的內容是讀多寫少的。因此,Hive中不建議對數據的改寫,所有的數據都是在載入的時候確定好的。而資料庫中的數據通常是需要經常進行修改的,因此可以使用 INSERT INTO … VALUES 添加數據,使用 UPDATE … SET修改數據。
1.4.4 索引
Hive在載入數據的過程中不會對數據進行任何處理,甚至不會對數據進行掃描,因此也沒有對數據中的某些Key建立索引。Hive要訪問數據中滿足條件的特定值時,需要暴力掃描整個數據,因此訪問延遲較高。由於 MapRece 的引入, Hive 可以並行訪問數據,因此即使沒有索引,對於大數據量的訪問,Hive 仍然可以體現出優勢。資料庫中,通常會針對一個或者幾個列建立索引,因此對於少量的特定條件的數據的訪問,資料庫可以有很高的效率,較低的延遲。由於數據的訪問延遲較高,決定了 Hive 不適合在線數據查詢。
1.4.5 執行
Hive中大多數查詢的執行是通過 Hadoop 提供的 MapRece 來實現的。而資料庫通常有自己的執行引擎。
1.4.6 執行延遲
Hive 在查詢數據的時候,由於沒有索引,需要掃描整個表,因此延遲較高。另外一個導致 Hive 執行延遲高的因素是 MapRece框架。由於MapRece 本身具有較高的延遲,因此在利用MapRece 執行Hive查詢時,也會有較高的延遲。相對的,資料庫的執行延遲較低。當然,這個低是有條件的,即數據規模較小,當數據規模大到超過資料庫的處理能力的時候,Hive的並行計算顯然能體現出優勢。
1.4.7 可擴展性
由於Hive是建立在Hadoop之上的,因此Hive的可擴展性是和Hadoop的可擴展性是一致的(世界上最大的Hadoop 集群在 Yahoo!,2009年的規模在4000 台節點左右)。而資料庫由於 ACID 語義的嚴格限制,擴展行非常有限。目前最先進的並行資料庫 Oracle 在理論上的擴展能力也只有100台左右。
1.4.8 數據規模
由於Hive建立在集群上並可以利用MapRece進行並行計算,因此可以支持很大規模的數據;對應的,資料庫可以支持的數據規模較小。
❻ java中怎麼實現查詢出hive下所有資料庫下表名
try {
Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
String selectSql = "select * from db.data where address = '11111111'";
Connection connect = DriverManager.getConnection("jdbc:hive://192.168.xx.xx:10000/db", "xxx", "xxx");
PreparedStatement state = null;
state = connect.prepareStatement(selectSql);
ResultSet resultSet = state.executeQuery();
while (resultSet != null && resultSet.next()) {
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
❼ 如何在Java中執行Hive命令或HiveQL
Java在1.5過後提供了ProcessBuilder根據運行時環境啟動一個Process調用執行運行時環境下的命令或應用程序(1.5以前使用Runtime),關於ProcessBuilder請參考Java相關文檔。調用代碼如下:
String sql="show tables; select * from test_tb limit 10";
List<String> command = new ArrayList<String>();
command.add("hive");
command.add("-e");
command.add(sql);
List<String> results = new ArrayList<String>();
ProcessBuilder hiveProcessBuilder = new ProcessBuilder(command);
hiveProcess = hiveProcessBuilder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(
hiveProcess.getInputStream()));
String data = null;
while ((data = br.readLine()) != null) {
results.add(data);
}
其中command可以是其它Hive命令,不一定是HiveQL。
❽ 如何在Java中執行Hive命令或HiveQL
這里所說的在Java中執行Hive命令或HiveQL並不是指Hive
Client通過JDBC的方式連接HiveServer(or
HiveServer2)執行查詢,而是簡單的在部署了HiveServer的伺服器上執行Hive命令。當然這是一個簡單的事情,平常我們通過Hive做簡單的數據分析實驗的時候,都是直接進入Hive執行HiveQL
通過進入Hive執行HiveQL,只能將分析結果列印到屏幕或是存入臨時表,如果想把分析結果寫入文件,或者對分析結果做進一步的分析,用程序做分析,就是為什麼要在Java中執行Hive命令。
Java在1.5過後提供了ProcessBuilder根據運行時環境啟動一個Process調用執行運行時環境下的命令或應用程序(1.5以前使用Runtime),關於ProcessBuilder請參考Java相關文檔。調用代碼如下:
String
sql="show
tables;
select
*
from
test_tb
limit
10";
List<String>
command
=
new
ArrayList<String>();
command.add("hive");
command.add("-e");
command.add(sql);
List<String>
results
=
new
ArrayList<String>();
ProcessBuilder
hiveProcessBuilder
=
new
ProcessBuilder(command);
hiveProcess
=
hiveProcessBuilder.start();
BufferedReader
br
=
new
BufferedReader(new
InputStreamReader(
hiveProcess.getInputStream()));
String
data
=
null;
while
((data
=
br.readLine())
!=
null)
{
results.add(data);
}其中command可以是其它Hive命令,不一定是HiveQL。