
ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ Python์ ํตํด Hive๋ฅผ ์ปจํธ๋กคํ๋ ๋์ฆ๊ฐ ๋ฐ์ํ๋ค.
sqlalchemy๋ฅผ ํ์ฉํ์ฌ, create select insert๋ฅผ ๊ตฌํํ๋ค.
sqlalchemy ๋?
Python์์ ์ฌ์ฉ๊ฐ๋ฅํ ORM(Object-relational maping)์ด๋ค.
์ฆ, ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ๋ฐ์ดํฐ๋ฅผ Objectํ๋์ ๋งคํํด์ค๋ค๋ ๊ฒ์ด๋ค. ์ฌ์ค DB์ ์คํค๋ง์ Object๋ ์๋ก ๊ธฐ์กด๋ถํฐ ํธํ๊ฐ๋ฅ์ฑ์ ๋๊ณ ๋ง๋ค์ด์ง ๊ฒ์ด ์๋๊ธฐ์ ๋ถ์ผ์น๊ฐ ๋ฐ์ํ๋๋ฐ,, ORM์ ๊ฐ์ฒด ๊ฐ์ ๊ด๊ณ๋ฅผ ๋ฐํ์ผ๋ก SQL๋ฌธ์ ์๋์ผ๋ก ์์ฑํ์ฌ ์ด๋ฌํ ๋ถ์ผ์น๋ฅผ ํด๊ฒฐํ๋ค.
์ด๋ฅผ ํตํด์ ์ฟผ๋ฆฌ๋ฅผ ์คํํ ์๋ ์๊ณ , Python์ Dataframe๊ณผ ๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ์ ์ฐ๊ฒฐํ ์ ์๋ค.

Hive-Python ์ฐ๋
1. select
from sqlalchemy import create_engine
engine = create_engine('hive://localhost:10000')
# select๋ฌธ
df = pd.read_sql("select * from db.table", engine)
2. Create
from sqlalchemy import create_engine
engine = create_engine('hive://localhost:10000')
# Create
db = db_name
table = table_name
schema = '(`val1` string, ' \
'`val2` Date, ' \
'`val3` int) '
query = ('''CREATE TABLE IF NOT EXISTS %s.%s %s
PARTITIONED BY (year int, month int, day int)
STORED AS PARQUET
''') % (db, table, schema)
engine.execute(query)
# PARTITIONED BY: ํํฐ์
๋์ ํตํด์ ๋ฐ์ดํฐ๋ฅผ ๋ถํ ํ๋ค (๋ฐ์ดํฐ ์์ ์ ํํ์ฌ ์ฑ๋ฅ์ ํฅ์์ํฌ์ ์๋ค)
# STORED AS PARQUET: ์นผ๋ผ๊ธฐ๋ฐ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ค
3. Insert
from sqlalchemy import create_engine
engine = create_engine('hive://localhost:10000')
# Insert๋ฌธ
df.to_sql(schema=db, name=table, con=engine,
index=False, method='multi', if_exists='append')
# index: df์ index๋ฅผ db์ ์นผ๋ผ์ผ๋ก ์ถ๊ฐํ ์ง ์ฌ๋ถ
# method: multi์ผ ๊ฒฝ์ฐ, ๋ค์์ ํ์ ๋์์ผ๋ก ํ๋ค
# if_exists: ๋ง์ฝ table์ด ์กด์ฌํ ๊ฒฝ์ฐ, ๋ค์ ๋ฐ์ดํฐ๋ฅผ ๋ถ์ธ๋ค
์ด๋ฅผ ํด๋์คํํ๋ฉด ์๋์ ๊ฐ๋ค.
์ฐธ๊ณ
https://moons08.github.io/programming/Hive_Partition/
https://moons08.github.io/programming/Hive_Table/#parquet
https://ulfrid.github.io/python/python-sqlalchemy/
'Engineering ๐ป > BigData' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Spark] Exception while deleting Spark temp dir ์๋ฌ ํด๊ฒฐ (0) | 2022.02.18 |
|---|---|
| [Hadoop] Spark ๋์ ๋จ๊ณ (0) | 2022.01.18 |
| [Hadoop] ์ค์ผ์คํธ๋ ์ด์ (feat. Oozie, Airflow) (0) | 2022.01.13 |
| [Hadooop] ๋ถ์์ฉ SQL ์์ง (feat. Hive, Impala, Presto) (0) | 2022.01.12 |
| [Hadoop] ์ฐ์ฐ ํ๋ ์์ํฌ (feat. MapReduce, Spark, Flink) (0) | 2022.01.11 |