본 문서는 Elasticsearch 7.7.1 을 ES-Hadoop 을 이용해 Hive 2.3.7 로 접속하고 Beeline 으로 JDBC 연결 하는 방법을 기술한다. (Hadoop 2.10.0 설치)
설치 후 HiveServer2 서비스를 실행하여 Beeline 클라이언트로 JDBC 연결을 하고, ES의 index 에 대해 select 하고 insert 하는 테스트를 수행해 본다.
– 설치 방식은 단일 서버에 가상-분산 모드 기준으로 설정한다.
– 이 설치 내용을 바탕으로 다음에는 Spark SQL 도 구성하여 기술할 예정이다.

[참고문서]
- https://jaceklaskowski.gitbooks.io/mastering-spark-sql/
- https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients
- https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2
- https://hadoop.apache.org/docs/r2.10.0/hadoop-project-dist/hadoop-common/SingleCluster.html#Pseudo-Distributed_Operation
[다운로드]
- Hadoop (naver) http://mirror.navercorp.com/apache/hadoop/common/
- Hive (naver) http://mirror.navercorp.com/apache/hive/
- Spark (naver) http://mirror.navercorp.com/apache/spark/
- ES-Hadoop https://www.elastic.co/kr/downloads/past-releases#es-hadoop
- Elasticsearch https://www.elastic.co/kr/downloads/past-releases#elasticsearch
설치 디렉토리 구조
- Hadoop 2.10.0 : hive 설치를 위해서 필요
- bin : hadoop fs, hdfs dfs, hdfs namenode -format
- sbin : start/stop-dfs.sh, start/stop-yarn.sh
- etc/hadoop : 설정파일들(xml, env.sh)
- postgresql 12.3 : hive 의 metastore 용 db
- $PG_DATA
- pg_hba.conf: OS 계정으로 trust 접속 가능하도록 설정
(별도의 user를 생성하거나 password 사용하지 말것: 골치 아파짐) - postgresql.conf: listen_addresses 또는 port 설정 (외부접속)
- pg_hba.conf: OS 계정으로 trust 접속 가능하도록 설정
- hive_metastore : database 생성
- $PG_DATA
- Hive 2.3.7 : metastore 로 스키마를 관리하고 hiveserver2 로 JDBC 연결
- bin : hive, schematool, beeline
- conf : 설정파일들 (xml, env.sh)
- Elasticsearch 7.7.1 : hadoop 과 루씬 기반의 검색엔진 (저장소로 사용)
- index : /_mapping, /_search
- extraJars : es-hadoop, graphframe 등 외부 라이브러리 파일들
설치 순서도 위와 같다. (적어도 hadoop, pg, hive 는 한묶음)
1. Hadoop 설치
** Apache 공식문서 Link
a. 설정
<!-- core-site.xml --> <configuration> <property> <name>fs.defaultFS</name> <value>hdfs://<IP or Hostname>:9000</value> </property> <!-- hive 작업시 insert 할 때 hive 계정으로 임시 파일 생성 (파일시스템 계정과 동일해야 권한 오류 발생 안함) ** 디렉토리 생성 "mkdir /tmp/hadoop-data" --> <property> <name>hadoop.tmp.dir</name> <value>/tmp/hadoop-temp</value> </property> <!-- [user] 는 OS 사용자 계정 --> <property> <name>hadoop.proxyuser.[user].groups</name> <value>*</value> </property> <property> <name>hadoop.proxyuser.[user].hosts</name> <value>*</value> </property> </configuration>
<!-- hdfs-site.xml --> <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <!-- $HADOOP_HOME/data 디렉토리 생성 --> <property> <name>dfs.namenode.name.dir</name> <value>/Users/bgmin/Servers/hadoop/data/namenode</value> </property> <property> <name>dfs.datanode.data.dir</name> <value>/Users/bgmin/Servers/hadoop/data/datanode</value> </property> </configuration>
<!-- yarn-site.xml --> <configuration> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> <property> <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name> <value>org.apache.hadoop.mapred.ShuffleHandler</value> </property> <property> <name>yarn.resourcemanager.hostname</name> <value>minmac</value> </property> <property> <name>yarn.acl.enable</name> <value>0</value> </property> <property> <name>yarn.nodemanager.env-whitelist</name> <value>JAVA_HOME,HADOOP_COMMON_HOME,HADOOP_HDFS_HOME, HADOOP_CONF_DIR,CLASSPATH_PERPEND_DISTCACHE, HADOOP_YARN_HOME,HADOOP_MAPRED_HOME</value> </property> </configuration>
<!-- mapred-site.xml --> <configuration> <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> <!-- 메모리 설정 https://blrunner.tistory.com/103 --> <property> <name>mapreduce.map.memory.mb</name> <value>2048</value> </property> <property> <name>mapreduce.reduce.memory.mb</name> <value>4096</value> </property> </configuration>
## slaves
## localhost 지우고 datanode 의 hostname 입력
ubuntu1
## ~/.zshrc 또는 ~/.bash_profile 또는 hadoop-env.sh export JAVA_HOME=`/usr/libexec/java_home` export SCALA_HOME=/Users/bgmin/Servers/scala # Hadoop 2.10.0 export HADOOP_HOME=/Users/bgmin/Servers/hadoop export HADOOP_INSTALL=$HADOOP_HOME export HADOOP_MAPRED_HOME=$HADOOP_HOME export HADOOP_COMMON_HOME=$HADOOP_HOME export HADOOP_HDFS_HOME=$HADOOP_HOME export YARN_HOME=$HADOOP_HOME export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib/native"
b. 시동 (start)
## ssh 설정 확인 : password 없이 localhost 진입해야함 ## --> 문제 있을시 ssh_config 설정 또는 authorized_keys 확인 $ ssh localhost $ cd $HADOOP_HOME ## [필수] namenode 포맷 $ bin/hadoop namenode -format ## 서비스 시동 $ sbin/start-dfs.sh $ sbin/start-yarn.sh ## 프로세스 확인 $ jps -lm 1297 org.apache.hadoop.yarn.server.nodemanager.NodeManager 901 org.apache.hadoop.hdfs.server.namenode.NameNode 981 org.apache.hadoop.hdfs.server.datanode.DataNode 97078 sun.tools.jps.Jps -lm 1080 org.apache.hadoop.hdfs.server.namenode.SecondaryNameNode 1213 org.apache.hadoop.yarn.server.resourcemanager.ResourceManager 36574 org.apache.hadoop.util.RunJar /Users/bgmin/Servers/hive/lib/hive-metastore-2.3.7.jar org.apache.hadoop.hive.metastore.HiveMetaStore
c. 확인 (verify)
open browser http://minmac:50070/
## hive 를 위한 hdfs 디렉토리 생성 $ bin/hdfs dfs -mkdir /tmp $ bin/hdfs dfs -chmod g+w /tmp $ bin/hdfs dfs -mkdir -p /user/hive/warehouse $ bin/hdfs dfs -chmod g+w /user/hive/warehouse ## hdfs 디렉토리 확인 ## 그외 copyFromLocal, chown -R, chmod 777 등.. 참고 $ bin/hdfs dfs -ls /user/hive/warehouse $ bin/hdfs dfs -getfacl /user/hive/warehouse # 권한 조회
d. 정지 (stop)
$ cd $HADOOP_HOME $ sbin/stop-yarn.sh $ sbin/stop-dfs.sh

2. Postgresql 설치
## Mac OS 의 경우 'brew install postgresql' 로 손쉽게 설치 ## 시작: start ## - 종료: stop, 상태확인: status $ pg_ctl -D $PG_DATA start ## hive 를 위한 metastore 생성 $ createdb hive_metastore --encoding='utf-8' --locale=ko_KR.utf8 ## login 확인 (password 없이 trust 로 인증) $ psql -h localhost -p 5432 -U bgmin hive_metastore > \c ## 현재 데이터베이스 또는 변경 > \d ## 테이블 리스트 > \q ## 나가기
3. Hive 설치
** 참고 문서 ==> link
a. 설정 파일
<!-- hive-site.xml --> <configuration> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:postgresql://localhost:15432/hive _metastore</value> </property> <!-- PG jdbc-driver jar 파일은 $HIVE_HOME/lib 에 복사 --> <property> <name>javax.jdo.option.ConnectionDriverName</name> <value>org.postgresql.Driver</value> </property> <property> <name>javax.jdo.option.ConnectionUserName</name> <value>bgmin</value> <description>username to use against metastore database</description> </property> <!-- 드라이버 설정상의 username 사용 여부 (없으면 hive) https://www.simba.com/products/Hive/doc/JDBC_InstallGuide/content/jdbc/hi/authoptions.htm --> <property> <name>hive.server2.enable.doAs</name> <value>true</value> </property> <property> <name>hive.metastore.warehouse.dir</name> <value>hdfs://localhost:9000/user/hive/warehouse</value> </property> <!-- hive 런타임에 사용될 외부 jar 등록 (comma 구분) ** 주의: file:// 또는 hdfs:// 를 명시해야 함 (jps 확인) 로딩 안된 경우, add jar hdfs://<path> 직접 실행 ** 대상: ES 연결이 필요하므로, es-hadoop 과 httpclient 등록 --> <property> <name>hive.aux.jars.path</name> <value>file:///home/bgmin/Servers/extraJars/commons-httpclient-3.1.jar, file:///home/bgmin/Servers/extraJars/elasticsearch-hadoop-7.7.1.jar</value> <!-- <value>hdfs:///user/hive/lib/commons-httpclient-3.1.jar,hdfs:/// user/hive/lib/elasticsearch-hadoop-7.7.1.jar</value> --> <description>elasticsearch-hadoop-7.7.1.jar</description> </property> </configuration>
<!-- hive-env.sh --> ## ~/.zshrc 또는 ~/.bash_profile 환경 변수 선언 export SERVER_ROOT=/Users/bgmin/Servers export HADOOP_HOME=$SERVER_ROOT/hadoop export HADOOP_HEAPSIZE=512 export HIVE_HOME=$SERVER_ROOT/hive export HIVE_CONF_DIR=$HIVE_HOME/conf ## 혹시 몰라 여기도 import jar 선언 (hive-site.xml) export HIVE_AUX_JARS_PATH=$SERVER_ROOT/extraJars/elasticsearch-hadoop-7.7.1.jar,$SERVER_ROOT/extraJars/commons-httpclient-3.1.jar
b. 시동 및 확인
[참고] Creating Hive table : Getting started – DDL operations
$ cd $HIVE_HOME ## initSchema on postgresql ## -- 초기화 필요시 새 database 대상으로 실행 (또는 다 지우던지) $ bin/schematool -initSchema -dbType postgres $ bin/schematool -validate -dbType postgres ## start hive $ bin/hive > create database es_test; > show databases; ## default, es_test 출력 > use es_test; > show tables; ## 아직 아무것도 없다 > quit;
c. hiveserver2 시동 및 jdbc 접속
$ cd $HIVE_HOME ## start hiveserver2 (백그라운드) $ nohup bin/hive --service hiveserver2 & ## beeline 이 hive 보다 가볍고 빠르다 $ bin/beeline > !connect jdbc:hive2://localhost:10000 bgmin ## -- 만약 패스워드 물으면 그냥 enter! > show databases; > use es_test; ## ES의 hive_test 인덱스 대상으로 external table 생성 > CREATE EXTERNAL TABLE es_test1( breed STRING, sex STRING ) STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler' TBLPROPERTIES( 'es.resource'='hive_test', 'es.nodes'='192.168.0.30:9200', 'es.net.http.auth.user'='<username>', 'es.net.http.auth.pass'='<password>', 'es.index.auto.create'='true', 'es.mapping.names'='breed:breed, sex:sex' ); > select * from es_test1; +-----------------+---------------+ | es_test1.breed | es_test1.sex | +-----------------+---------------+ | shibainu | male | | frenchie | female | | corgi | male | | greyhound | female | | sichu | male | +-----------------+---------------+ 5 rows selected (0.926 seconds) > insert overwrite table es_test1 values('bulldog', 'female'); WARNING: Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases. No rows affected (9.249 seconds) > select * from es_test1; +-----------------+---------------+ | es_test1.breed | es_test1.sex | +-----------------+---------------+ | shibainu | male | | frenchie | female | | corgi | male | | greyhound | female | | sichu | male | | bulldog | female | +-----------------+---------------+ 6 rows selected (0.129 seconds) > !close > !quit



4. Elasticsearch 설치
## hive_test 인덱스 삭제 curl -X DELETE "localhost:9200/hive_test?pretty" ## hive_test 인덱스 생성 (shards=1, replicas=0) curl -X PUT "localhost:9200/hive_test?pretty" -H 'Content-Type: application/json' -d' { "settings" : { "index" : { "number_of_shards" : 1, "number_of_replicas" : 0 } } } ' ## schema 설정 curl -X PUT "localhost:9200/hive_test/_mapping?pretty" -H 'Content-Type: application/json' -d' { "properties": { "breed": { "type": "keyword" }, "sex": { "type": "keyword" } } }' ## 문서 하나 색인(생성) curl -X POST "localhost:9200/hive_test/_doc/?pretty" -H 'Content-Type: application/json' -d' { "breed": "greyhound", "sex": "male" } ' ## 여러 문서를 한번에 색인(생성) curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d' { "index" : { "_index" : "hive_test", "_id" : "1" } } { "breed": "shibainu", "sex": "male" } { "index" : { "_index" : "hive_test", "_id" : "2" } } { "breed": "frenchie", "sex": "female" } { "index" : { "_index" : "hive_test", "_id" : "3" } } { "breed": "corgi", "sex": "male" } ' ## 색인된 문서 조회 curl -X GET "localhost:9200/hive_test/_search?pretty" ## 브라우저 조회시 (q=필드명:조건값) ## ==> http://192.168.0.30:9200/hive_test/_search?pretty&q=*:*

[참고] Hive Service Port
- Hive Server 2
- default port=10000, thrift protocol
- ENV Variable : HIVE_PORT=<port>
** 참고문서 Setting-up Hive-Server2
hive.server2.thrift.port – default 10000.
hive.server2.thrift.bind.host – TCP interface to bind to. - Service for programatically (Thrift/JDBC) connecting to Hive
- Web UI http://minubt:10002/
- Metastore
- default port=9083, thrift protocol
- hive-site.xml : hive.metastore.uris=<URL>
- Web UI 없음
Tip: Update Hive Metastore
core-site.xml 의 fs.defaultFS 을 특정 호스트로 지정했는데도, hive 상에서 개체 생성시 localhost 만을 가리키는 경우가 있다. 그런 경우엔 metatool 로 listFSRoot 를 확인해보고, location 의 namenode 위치를 강제로 변경한다. (명령어 -updateLocation)
## hive 카탈로그가 가리키는 위치를 확인
$ bin/metatool -listFSRoot
Listing FS Roots..
hdfs://localhost:9000/user/hive/warehouse/es_test.db
hdfs://localhost:9000/user/hive/warehouse
## localhost 을 minubt 라는 namenode 로 강제 변경한다
$ bin/metatool -updateLocation hdfs://minubt:9000 hdfs://localhost:9000
## 이후 hive 개체들은 namenode를 포함하는 FSRoot 아래로 생성된다
$ bin/metatool -listFSRoot
Listing FS Roots..
hdfs://minubt:9000/user/hive/warehouse/es_test.db
hdfs://minubt:9000/user/hive/warehouse
** TIP!!
Hive 실행시 Guava 버전 충돌 오류로 main 조차 시작이 안되는 경우
==> hadoop 의 hdfs lib 내의 jar 파일을 hive/lib 로 복사하여 일치 시키면 됨
“`
$ rm /opt/shared/apache-hive-3.1.2-bin/lib/guava-19.0.jar
$ cp /opt/shared/hadoop-3.2.1/share/hadoop/hdfs/lib/guava-27.0-jre.jar /opt/shared/apache-hive-3.1.2-bin/lib/
“`
** 참고문서
https://issues.apache.org/jira/browse/HIVE-22915?focusedCommentId=17044153&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-17044153
좋아요좋아요
** beeline 콘솔에서 UDF 생성하기
hdfs dfs -put -f target/agens-spark-connector-full-1.0-dev.jar /user/agens/
add jar hdfs://minmac:9000/user/agens/agens-spark-connector-full-1.0-dev.jar;
list jars;
** delete jar 안됨! ==> spark-thriftserver 를 재시동해야 함
create or replace temporary function agensUdf as ‘net.bitnine.hive.udf.AgensUdf’ using jar ‘hdfs://minmac:9000/user/agens/agens-spark-connector-full-1.0-dev.jar’;
select agensUdf(‘TEST’) as msg;
drop function agensUdf;
** global 함수로 등록되면 spark session 에서도 사용 가능 (default.agensUdf)
*
spark> spark.sql(“select agensUdf(‘TEST’) as msg”).show(false)
좋아요좋아요
## hive_test 인덱스 삭제
DELETE /hive_test?pretty
## hive_test 인덱스 생성 (shards=1, replicas=0)
PUT /hive_test?pretty
{
“settings” : {
“index” : {
“number_of_shards” : 1,
“number_of_replicas” : 0
}
}
}
## schema 설정
PUT /hive_test/_mapping?pretty
{
“properties”: {
“breed”: { “type”: “keyword” },
“sex”: { “type”: “keyword” }
}
}
## 문서 하나 색인(생성)
POST /hive_test/_doc/?pretty
{
“breed”: “greyhound”, “sex”: “male”
}
## 여러 문서를 한번에 색인(생성)
POST /_bulk?pretty
{ “index” : { “_index” : “hive_test”, “_id” : “1” } }
{ “breed”: “shibainu”, “sex”: “male” }
{ “index” : { “_index” : “hive_test”, “_id” : “2” } }
{ “breed”: “frenchie”, “sex”: “female” }
{ “index” : { “_index” : “hive_test”, “_id” : “3” } }
{ “breed”: “corgi”, “sex”: “male” }
## 색인된 문서 조회
GET /hive_test/_search?pretty
## hive test
CREATE EXTERNAL TABLE tbl_dogs(
breed STRING,
sex STRING
) STORED BY ‘org.elasticsearch.hadoop.hive.EsStorageHandler’
TBLPROPERTIES(
‘es.resource’=’hive_test’,
‘es.nodes’=’192.168.0.**:9200’,
‘es.net.http.auth.user’=’****’,
‘es.net.http.auth.pass’=’****’,
‘es.index.auto.create’=’true’,
‘es.mapping.names’=’breed:breed, sex:sex’
);
좋아요좋아요
스파크 소스가 지원하는 hadoop 버전을 알아볼 수 있다.
$ cd spark
$ grep \<hadoop\.version\> -r pom.xml
** 출처 https://xuechendi.github.io/2019/04/16/spark-and-hadoop-build-from-source
스파크 커스텀 빌드 수행해서 그자체로 사용하려면 (프로파일 추가)
$ ./build/mvn -Pyarn -Phive -Phive-thriftserver -Phadoop-2.7 -Dhadoop.version=2.10.1 -DskipTests clean package
또는 스파크 빌드 후 배포판 만들기까지 수행하려면 이것으로 (프로파일 추가)
$ ./dev/make-distribution.sh –name spark-2.4.7-src-hadoop2.10 –pip –r –tgz -Phadoop-2.7 -Dhadoop.version=2.10.1 -Phive -Phive-thriftserver -Pyarn
** 출처 https://spark.apache.org/docs/2.4.7/building-spark.html
그 외 Spark Install 참고문서
https://github.com/GalvanizeDataScience/spark-install
좋아요Liked by 1명