메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

Bigdata, Hadoop ecosystem, Semantic IoT등의 프로젝트를 진행중에 습득한 내용을 정리하는 곳입니다.
필요한 분을 위해서 공개하고 있습니다. 문의사항은 gooper@gooper.com로 메일을 보내주세요.


hive Hive java connection 설정

구퍼 2013.04.01 15:06 조회 수 : 2013

출처 : http://promaster.tistory.com/84

 

어찌되었든 DB만은 할수없는 일이다.
좋은(비싸기만 한것말고 적재적소의 데이터베이스) DB에 잘 설계된 데이터구조를 올려놓고 나면
잘만들어진 프로그램이 좋은 인터페이스 역할을 해야 좋은데이터가 만들어지는것이지.

DB혼자 잘나바야 데이터 넣기도 어렵고
개발혼자 잘나바야 데이터 꺼내서 활용하기도 어렵다.

개발과 DB는 어찌되었든 같이 조화가 되어야지 불화(?) 가 되어서는 안되는것 같다.

아무튼.
데이터 insert , select 를 위해서 hive를 이용해서 데이터 조작을 위한 테스트를 진행하려고 한다.

준비사항 :
1. hive-0.8.1-bin.tar.gz 안의 라이브러리들.
2. 개발툴 ( 나는 eclipse )
3. WAS 아무거나 ( 나는 tomcat - was라고 치자..... )

1. 설정 (관련 라이브러리 추가)


아래3가지 ( libfb , slf4j 2가지를 처음에 빼고 나머지만 라이브러리에 추가 했더니 에러도 잘 안나오고
실행은 안되고 알수가 없었다. 꼭 추가하길
)

이클립스에 추가되어야할 라이브러리들.

hive-jdbc-버전.jar

hive-exec-버전.jar

hive-metastore-버전.jar

hive-service-버전.jar

hadoop-core-버전.jar

commons-logging-버전.jar

log4j-버전.jar

libfb버전.jar

slf4j-api-버전.jar

slf4j-log4j12-버전.jar

2. hive server 실행

Hive를 mysql에 연결한 작업까지 하고나서 이제 Hive 서비스를 띄운다.
(물론 HIVE_HOME 설정은 되어있는 상태이며 bin디렉토리까지 path로 잡아놓은 상태 이고 mysql 로 띄운상태이다.)

[hadoop@master1 ~]$hive --service hiveserver &
WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated. Please use org.apache.hadoop.log.metrics.EventCounter in all the log4j.properties files.
Hive history file=/home/hadoop/hive/log/tansactionhist/hive_job_log_hadoop_201208041919_1622721562.txt

아래는 그냥 로그파일에 찍히는 내용을 보고자띄움.

[hadoop@master1 ~]$tail -f /home/hadoop/hive/log/tansactionhist/hive_job_log_hadoop_201208041919_1622721562.txt

2. 테스트 (테스트는 https://cwiki.apache.org/Hive/hiveclient.html 에 있는 내용을 테스트함 )

테스트를 위해서 참고한 apache.org에 소스가 있으니 그대로 가져와도 된다.

아래는 해당 사이트에 있는 소스임 여기서 내서버와 관련된 설정만 바꾸도록 한다.

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class HiveJdbcClient {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";

/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://192.168.0.141:10000/default", "", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.executeQuery("drop table " + tableName);
ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
// describe table
sql = "describe " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1) + "t" + res.getString(2));
}

// load data into table
// NOTE: filepath has to be local to the hive server
// NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per line
String filepath = "/home/hadoop/test.txt"; // <---- 이걸 참고할것 아래에 내용 이어서.
sql = "load data local inpath '" + filepath + "' into table " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);

// select * query
sql = "select * from " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(String.valueOf(res.getInt(1)) + "t" + res.getString(2));
}
}

}

위의 파일경로와 파일명이 써있는부분의 파일생성은 hive 서버를 작동시킨 곳에다가 파일을 넣는다.
본인이 tomcat를 로컬에다가 띄웠다고 로컬에 넣는것이 아닌 hive서버 경로이다.
또한 그냥 단순히 apache.org에 있는 내용을 vi 로 작성했더니 인식을 못하더라 ;;;;; 예제 있는 쉘그대로 실행할것.

12028D50501D1E58347E23

[hadoop@master1 ~]$echo -e '1x01foo' > /home/hadoop/test.txt
[hadoop@master1 ~]$echo -e '2x01bar' >> /home/hadoop/test.txt

아무튼 위처럼 파일을 생성하고나서 실행를 해보면 .

3. 결과

* 아래는 로그파일에 찍힌 내용

Hive history file=/home/hadoop/hive/log/tansactionhist/hive_job_log_hadoop_201208041919_859275775.txt
OK
OK
OK
OK
Copying data from file:/home/hadoop/test.txt
Copying file: file:/home/hadoop/test.txt
Loading data to table default.testhivedrivertable
OK
OK

* 아래는 console 에 찍힌 내용

Running: show tables 'testHiveDriverTable'
testhivedrivertable
Running: describe testHiveDriverTable
key int
value string
Running: load data local inpath '/home/hadoop/test.txt' into table testHiveDriverTable
Running: select * from testHiveDriverTable
1 foo
2 bar

* hive로 들어가서 select 를 해본내용

[hadoop@master1 ~]$ hive
WARNING: org.apache.hadoop.metrics.jvm.EventCounter is deprecated. Please use org.apache.hadoop.log.metrics.EventCounter in all the log4j.properties files.
Logging initialized using configuration in file:/usr/local/hive/conf/hive-log4j.properties
Hive history file=/home/hadoop/hive/log/tansactionhist/hive_job_log_hadoop_201208042146_1805362014.txt
hive> select *From testHiveDriverTable;
OK
1 foo
2 bar
Time taken: 3.097 seconds
hive>

* Hadoop 관리자 모습 (test파일이 추가된모습 )

140FFA4B501D1E291F532A

번호 제목 글쓴이 날짜 조회 수
681 [Cloudera 6.3.4, Kudu]]Service Monitor에서 사용하는 metric중에 일부를 blacklist로 설정하여 모니터링 정보 수집 제외하는 방법 gooper 2022.07.08 31
680 파일은 남겨두고 파일 내용만 지우고자 할 때. 총관리자 2017.08.30 32
679 Cloudera Hadoop and Spark Developer Certification 준비(참고) 총관리자 2018.05.16 32
678 Failed to write to server: (no server available): 총관리자 2022.01.17 32
677 [Kerberos]병렬 kinit 호출시 cache파일이 손상되어 Bad format in credentials cache 혹은 No credentials cache found 혹은 Internal credentials cache error 오류 발생시 gooper 2023.01.20 32
676 restaurant-controller,에서 등록 예시 총관리자 2022.04.30 33
675 fuseki에서 제공하는 script중 s-post를 사용하는 예문 총관리자 2017.09.15 34
674 AnalysisException: Incomplatible return type 'DECIMAL(38,0)' and 'DECIMAL(38,5)' of exprs가 발생시 조치 총관리자 2021.07.26 34
673 ServerInfo객체파일 총관리자 2016.07.21 35
672 spark에서 hive table을 읽어 출력하는 예제 소스 총관리자 2017.03.09 35
671 core 'gc_shard3_replica2' is already locked라는 오류가 발생할때 조치사항 총관리자 2017.09.14 35
670 tar를 이용한 리눅스 백업 총관리자 2018.05.13 35
669 Oracle NLOB type의 데이터를 import하는 경우 No Java type for SQL type 2011 for column rst와 같은 오류 발생시 조치사항 총관리자 2022.01.14 35
668 [TLS/SSL]Kudu Tablet Server설정 총관리자 2022.05.13 35
667 kerberos연동된 CDH 6.3.4에서 default realm값이 잘못된 상태에서 서비스 기동시 오류 gooper 2022.10.14 35
666 S2RDF모듈의 실행부분만 추출하여 별도록 실행하는 방법(draft) 총관리자 2016.06.14 36
665 5건의 triple data를 이용하여 특정 작업 폴더에서 작업하는 방법/절차 총관리자 2016.06.16 36
664 Github를 이용하는 전체 흐름 이해하기 총관리자 2016.11.18 36
663 [vi] test.nq파일에서 특정문자열(예, <>)을 찾아서 포함되는 라인을 삭제한 동일한 이름의 파일을 만드는 방법 총관리자 2017.01.25 36
662 CM의 Impala->Query tab에서 FINISHED query가 보이지 않는 현상 총관리자 2021.08.31 36

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로