[Apache Spark] Spark SQL 아파치 스파크 SQL 개요 

 

1 스파크 SQL 들어가며

pip install pyspark로 파이썬 스파크를 설치하게 되면 스파크세션을 만들어서 스파크 SQL로 들어갈 수 있는 여정을 시작할 수 있다. 스파크 Getting Started를 참조해서 스파크 세션을 생성한다.

그리고 나서, 그 유명한 붓꽃 데이터(iris.csv) 데이터를 로컬 컴퓨터에서 불러와서 스파크 데이터프레임으로 생성시킨다.

from pyspark.sql import *

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option") \
    .getOrCreate()
    
iris_df = spark.read.csv("data/iris.csv", inferSchema = True, header = True)

iris_df.show(5)
+------------+-----------+------------+-----------+-------+
|sepal.length|sepal.width|petal.length|petal.width|variety|
+------------+-----------+------------+-----------+-------+
|         5.1|        3.5|         1.4|        0.2| Setosa|
|         4.9|        3.0|         1.4|        0.2| Setosa|
|         4.7|        3.2|         1.3|        0.2| Setosa|
|         4.6|        3.1|         1.5|        0.2| Setosa|
|         5.0|        3.6|         1.4|        0.2| Setosa|
+------------+-----------+------------+-----------+-------+
only showing top 5 rows
 

1.1 스파크 SQL

다음으로 데이터프레임에 SQL을 적용시킬 수 있는 객체를 별도로 만든다. 이때 스파크데이터프레임.createOrReplaceTempView("객체명") 메소드를 사용한다. spark.sql() 메쏘드를 사용해서 SQL 문을 던져 원하는 결과를 얻을 수 있다.

iris_df.createOrReplaceTempView("iris")

spark.sql("SELECT * FROM iris LIMIT 5").show()
+------------+-----------+------------+-----------+-------+
|sepal.length|sepal.width|petal.length|petal.width|variety|
+------------+-----------+------------+-----------+-------+
|         5.1|        3.5|         1.4|        0.2| Setosa|
|         4.9|        3.0|         1.4|        0.2| Setosa|
|         4.7|        3.2|         1.3|        0.2| Setosa|
|         4.6|        3.1|         1.5|        0.2| Setosa|
|         5.0|        3.6|         1.4|        0.2| Setosa|
+------------+-----------+------------+-----------+-------+
 

1.2 스파크 SQL 스키마

테이블에 SQL 질의(Query)를 던지기 전에 가장 먼저 해야 되는 작업은 아마도 스카마(Schema) 구조를 파악하는 것이다. 이를 위해서 SQL DESCRIBE 명령어를 사용한다.

spark.sql("DESCRIBE iris").show()
+------------+---------+-------+
|    col_name|data_type|comment|
+------------+---------+-------+
|sepal.length|   double|   null|
| sepal.width|   double|   null|
|petal.length|   double|   null|
| petal.width|   double|   null|
|     variety|   string|   null|
+------------+---------+-------+
 

2 스파크 SQL 기본기 1

 

2.1 데이터 프레임 생성

createDataFrame() 메쏘드를 사용해서 스파크 데이터프레임을 작성한다. 그리고, 판다스 데이터프레임에서 스파크 데이터프레임도 생성이 가능하다. 앞써 spark.read_csv() 메쏘드, DataFrameReader를 사용해서 스파크 데이터프레임 생성하는 것도 가능하다.

df1 = spark.createDataFrame([(1, "andy", 20, "USA"), 
                             (2, "jeff", 23, "China"), 
                             (3, "james", 18, "USA")]).toDF("id", "name", "age", "country")

df1.printSchema
<bound method DataFrame.printSchema of DataFrame[id: bigint, name: string, age: bigint, country: string]>
df1.show()

# 판다스 데이터프레임에서 스파크 데이터프레임 생성
+---+-----+---+-------+
| id| name|age|country|
+---+-----+---+-------+
|  1| andy| 20|    USA|
|  2| jeff| 23|  China|
|  3|james| 18|    USA|
+---+-----+---+-------+
df2 = spark.createDataFrame(df1.toPandas())
df2.printSchema
<bound method DataFrame.printSchema of DataFrame[id: bigint, name: string, age: bigint, country: string]>
df2.show()
+---+-----+---+-------+
| id| name|age|country|
+---+-----+---+-------+
|  1| andy| 20|    USA|
|  2| jeff| 23|  China|
|  3|james| 18|    USA|
+---+-----+---+-------+
 

2.2 신규 필드 생성

dplyr 팩키지 mutate와 마찬가지로 신규 필드를 생성할 때는 withColumn() 메쏘드를 사용한다.

df2 = df1.withColumn("age2", df1["age"] + 1)
df2.show()
+---+-----+---+-------+----+
| id| name|age|country|age2|
+---+-----+---+-------+----+
|  1| andy| 20|    USA|  21|
|  2| jeff| 23|  China|  24|
|  3|james| 18|    USA|  19|
+---+-----+---+-------+----+
 

2.3 칼럼 추출 및 제거

dplyr 팩키지 select와 마찬가지로 원하는 변수 칼럼을 추출하고자 할 때는 select 메쏘드를 사용한다. 칼럼을 제거하고자 하는 경우 drop을 사용한다.

df2 = df1.select("id", "name")
df2.show()
+---+-----+
| id| name|
+---+-----+
|  1| andy|
|  2| jeff|
|  3|james|
+---+-----+
df1.drop("id", "name").show()
+---+-------+
|age|country|
+---+-------+
| 20|    USA|
| 23|  China|
| 18|    USA|
+---+-------+
 

2.4 관측점 행 추출

dplyr 팩키지 filter와 마찬가지로 원하는 관측점 행을 추출하고자 할 때는 동일한 명칭의 filter 메쏘드를 사용한다.

df1.filter(df1["age"] >= 20).show()
+---+----+---+-------+
| id|name|age|country|
+---+----+---+-------+
|  1|andy| 20|    USA|
|  2|jeff| 23|  China|
+---+----+---+-------+
 

2.5 그룹별 요약

그룹별 요약을 하는데 groupBy를 agg와 함께 사용한다. 이는 dplyr 팩키지 group_by + summarize와 동일한 개념이다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

df1.groupBy("country").agg({"age": "avg", "id": "count"}).show()
+-------+---------+--------+
|country|count(id)|avg(age)|
+-------+---------+--------+
|  China|        1|    23.0|
|    USA|        2|    19.0|
+-------+---------+--------+
 

2.6 사용자 정의함수(UDF)

사용자 정의함수(User Defined Function)을 작성하여 표준 SQL 구문에서 제공되지 않는 연산작업을 수행시킬 수 있다.

from pyspark.sql.functions import udf
upper_character = udf(lambda x: x.upper())

df1.select(upper_character(df1["name"])).show()
+--------------+
|<lambda>(name)|
+--------------+
|          ANDY|
|          JEFF|
|         JAMES|
+--------------+
 

2.7 데이터프레임 죠인

두개의 서로 다른 스파크 데이터프레임을 죠인(join)하는 것도 가능하다.

df1.show()
+---+-----+---+-------+
| id| name|age|country|
+---+-----+---+-------+
|  1| andy| 20|    USA|
|  2| jeff| 23|  China|
|  3|james| 18|    USA|
+---+-----+---+-------+
df2 = spark.createDataFrame([(1, "USA"), (2, "China")]).toDF("c_id", "c_name")
df2.show()
+----+------+
|c_id|c_name|
+----+------+
|   1|   USA|
|   2| China|
+----+------+
df1.join(df2, df1["id"] == df2["c_id"]).show()
+---+----+---+-------+----+------+
| id|name|age|country|c_id|c_name|
+---+----+---+-------+----+------+
|  1|andy| 20|    USA|   1|   USA|
|  2|jeff| 23|  China|   2| China|
+---+----+---+-------+----+------+
 

3 윈도우 함수

databricks, “Introducing Window Functions in Spark SQL Notebook”에서 데이터를 준비한다.

data = \
  [("Thin", "Cell Phone", 6000),
  ("Normal", "Tablet", 1500),
  ("Mini", "Tablet", 5500),
  ("Ultra thin", "Cell Phone", 5500),
  ("Very thin", "Cell Phone", 6000),
  ("Big", "Tablet", 2500),
  ("Bendable", "Cell Phone", 3000),
  ("Foldable", "Cell Phone", 3000),
  ("Pro", "Tablet", 4500),
  ("Pro2", "Tablet", 6500)]
  
df = spark.createDataFrame(data, ["product", "category", "revenue"])

df.createOrReplaceTempView("product")

start_df = spark.sql("SELECT category, product, revenue \
                      FROM product \
                      ORDER BY category, revenue DESC")
start_df.show()                      
+----------+----------+-------+
|  category|   product|revenue|
+----------+----------+-------+
|Cell Phone| Very thin|   6000|
|Cell Phone|      Thin|   6000|
|Cell Phone|Ultra thin|   5500|
|Cell Phone|  Foldable|   3000|
|Cell Phone|  Bendable|   3000|
|    Tablet|      Pro2|   6500|
|    Tablet|      Mini|   5500|
|    Tablet|       Pro|   4500|
|    Tablet|       Big|   2500|
|    Tablet|    Normal|   1500|
+----------+----------+-------+

제품군별로 가장 매출 차이를 찾아보고자 하는 사례를 만들어보자. LAG, LEAD를 OVER와 함께 사용하여 윈도우 함수를 적용하여 관측점을 이동시킬 수 있다. 하지만 제품군내에서 작업된 것은 아니라 시각적으로 불편한다.

start_df.createOrReplaceTempView("start_tbl")

reveune_query = """
    SELECT category, product, 
    LAG(revenue, 1) OVER (ORDER BY revenue) AS revenue_lag,
    revenue,
    LEAD(revenue, 1) OVER (ORDER BY revenue) AS revenue_lead
    FROM start_tbl
    """

spark.sql(reveune_query).show()
+----------+----------+-----------+-------+------------+
|  category|   product|revenue_lag|revenue|revenue_lead|
+----------+----------+-----------+-------+------------+
|    Tablet|    Normal|       null|   1500|        2500|
|    Tablet|       Big|       1500|   2500|        3000|
|Cell Phone|  Bendable|       2500|   3000|        3000|
|Cell Phone|  Foldable|       3000|   3000|        4500|
|    Tablet|       Pro|       3000|   4500|        5500|
|Cell Phone|Ultra thin|       4500|   5500|        5500|
|    Tablet|      Mini|       5500|   5500|        6000|
|Cell Phone|      Thin|       5500|   6000|        6000|
|Cell Phone| Very thin|       6000|   6000|        6500|
|    Tablet|      Pro2|       6000|   6500|        null|
+----------+----------+-----------+-------+------------+

PARTITION BY를 그룹 집단을 도입하게 되면 원하는 결과를 얻을 수 있게 된다.

reveune_query = """
    SELECT category, product, 
    LAG(revenue, 1) OVER (PARTITION BY category ORDER BY revenue) AS revenue_lag,
    revenue,
    LEAD(revenue, 1) OVER (PARTITION BY category ORDER BY revenue) AS revenue_lead
    FROM start_tbl
    """

spark.sql(reveune_query).show()
+----------+----------+-----------+-------+------------+
|  category|   product|revenue_lag|revenue|revenue_lead|
+----------+----------+-----------+-------+------------+
|    Tablet|    Normal|       null|   1500|        2500|
|    Tablet|       Big|       1500|   2500|        4500|
|    Tablet|       Pro|       2500|   4500|        5500|
|    Tablet|      Mini|       4500|   5500|        6500|
|    Tablet|      Pro2|       5500|   6500|        null|
|Cell Phone|  Bendable|       null|   3000|        3000|
|Cell Phone|  Foldable|       3000|   3000|        5500|
|Cell Phone|Ultra thin|       3000|   5500|        6000|
|Cell Phone|      Thin|       5500|   6000|        6000|
|Cell Phone| Very thin|       6000|   6000|        null|
+----------+----------+-----------+-------+------------+

ROW_NUMBER()를 도입하게 되면 각 그룹별 번호를 매길 수 있게 된다.

reveune_query = """
    SELECT category, product, 
    ROW_NUMBER() OVER(PARTITION BY category ORDER BY revenue) AS id,
    LAG(revenue, 1) OVER (PARTITION BY category ORDER BY revenue) AS revenue_lag,
    revenue,
    LEAD(revenue, 1) OVER (PARTITION BY category ORDER BY revenue) AS revenue_lead
    FROM start_tbl
    """

spark.sql(reveune_query).show()
+----------+----------+---+-----------+-------+------------+
|  category|   product| id|revenue_lag|revenue|revenue_lead|
+----------+----------+---+-----------+-------+------------+
|    Tablet|    Normal|  1|       null|   1500|        2500|
|    Tablet|       Big|  2|       1500|   2500|        4500|
|    Tablet|       Pro|  3|       2500|   4500|        5500|
|    Tablet|      Mini|  4|       4500|   5500|        6500|
|    Tablet|      Pro2|  5|       5500|   6500|        null|
|Cell Phone|  Bendable|  1|       null|   3000|        3000|
|Cell Phone|  Foldable|  2|       3000|   3000|        5500|
|Cell Phone|Ultra thin|  3|       3000|   5500|        6000|
|Cell Phone|      Thin|  4|       5500|   6000|        6000|
|Cell Phone| Very thin|  5|       6000|   6000|        null|
+----------+----------+---+-----------+-------+------------+

 

[출처] https://statkclee.github.io/bigdata/bigdata-spark-sql.html

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86307
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78757
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95505
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 901
45 [데이터분석][파이썬][python] 한글 글꼴 사용 (matplotlib) 졸리운_곰 2024.04.18 1360
44 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 1315
43 [데이터분석][파이썬][python] Awesome Dash Awesome file 졸리운_곰 2021.07.10 2340
42 [데이터분석][파이썬][python] ???? Introducing Dash ???? file 졸리운_곰 2021.07.10 1607
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1559
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1762
39 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1605
38 [데이터분석][데이터 사이언스][python][Dash] Python, Dash 및 Plotly를 사용하여 COVID-19 사례 데이터 시각화 file 졸리운_곰 2021.03.28 1501
37 [데이터분석][머신러닝] When not to use machine learning or AI Adventures in wishful thinking, nonstationarity, and pattern-finding / 기계 학습 또는 AI를 사용하지 않아야하는 경우 희망찬 사고, 비정상 성, 패턴 찾기의 모험 file 졸리운_곰 2021.03.28 21622
36 [MSA][머신러닝] 쿠버네티스 기반의 End2End 머신러닝 플랫폼 Kubeflow #1 - 소개 file 졸리운_곰 2021.03.21 1136
35 [데이터사이언스] 데이터 과학자를위한 3 가지 훌륭한 디자인 패턴, 3 Great Design Patterns for Data Scientists file 졸리운_곰 2021.03.04 780
34 [데이터분석] 시계열 데이터에 AI를 사용하는 이유는 무엇입니까? file 졸리운_곰 2021.02.28 1193
33 [데이터분석] AI 예측 및 이상 탐지를위한 시계열 데이터 전처리 file 졸리운_곰 2021.02.28 1031
32 [데이터분석] bitcoin analysis 비트 코인 시계열 데이터에 대한 AI 이상 탐지 file 졸리운_곰 2021.02.27 1592
31 [데이터분석 & 데이터 사이언스] How To Create a Data Science Portfolio Website file 졸리운_곰 2021.02.14 1824
30 [데이터수집4] 오픈 API 데이터 수집 (소셜미디어 데이터 수집) file 졸리운_곰 2020.06.12 1951
29 [데이터수집3] 관계형 데이터베이스 데이터 수집 file 졸리운_곰 2020.06.12 1317
28 [데이터수집2] 분산시스템 로그 수집 (빅데이터 수집) file 졸리운_곰 2020.06.12 1493
27 [데이터수집1] 웹 크롤링, 웹 스크래핑 file 졸리운_곰 2020.06.12 1804
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED