[pySpark, 파이썬 spark] Best Practices Writing Production-Grade PySpark Jobs

How to Structure Your PySpark Job Repository and Code

Using PySpark to process large amounts of data in a distributed fashion is a great way to manage large-scale data-heavy tasks and gain business insights while not sacrificing on developer efficiency.

In short, PySpark is awesome.
However, while there are a lot of code examples out there, there’s isn’t a lot of information out there (that I could find) on how to build a PySpark codebase— writing modular jobs, building, packaging, handling dependencies, testing, etc. — that could scale to a larger development team.

So, following a year+ working with PySpark I decided to collect all the know-hows and conventions we’ve gathered into this post (and accompanying boilerplate project)

In this post we’ll cover:

  • Structuring PySpark Jobs
  • Handling 3rd-party dependencies
  • Writing a PySpark Job
  • Unit Testing

Structuring our Jobs Repository

First, let’s go over how submitting a job to PySpark works:
spark-submit --py-files pyfile.py,zipfile.zip main.py --arg1 val1

When we submit a job to PySpark we submit the main Python file to run — main.py — and we can also add a list of dependent files that will be located together with our main file during execution.
These dependency files can be .py code files we can import from, but can also be any other kind of files. For example, .zip packages.

One of the cool features in Python is that it can treat a zip file as a directory as import modules and functions from just as any other directory.
All that is needed is to add the zip file to its search path.

import sys
sys.path.insert(0, jobs.zip)

now (assuming jobs.zip contains a python module called jobs) we can import that module and whatever that’s in it. For example:

from jobs.wordcount import run_job
run_job()

This will allow us to build our PySpark job like we’d build any Python project — using multiple modules and files — rather than one bigass myjob.py (or several such files)

Armed with this knowledge let’s structure out PySpark project…

Jobs as Modules

We’ll define each job as a Python module where it can define its code and transformation in whatever way it likes (multiple files, multiple sub modules…).

.
├── README.md
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py

The job itself has to expose an analyze function:

def analyze(sc, **kwargs):
   ...

and a main.py which is the entry point to our job — it parses command line arguments and dynamically loads the requested job module and runs it:

import pysparkif os.path.exists('jobs.zip'):
    sys.path.insert(0, 'jobs.zip')
else:
    sys.path.insert(0, './jobs')parser = argparse.ArgumentParser()
parser.add_argument('--job', type=str, required=True)
parser.add_argument('--job-args', nargs='*')
args = parser.parse_args()sc = pyspark.SparkContext(appName=args.job_name)
job_module = importlib.import_module('jobs.%s' % args.job)
job_module.analyze(sc, job_args)

To run this job on Spark we’ll need to package it so we can submit it via spark-submit …

Packaging

As we previously showed, when we submit the job to Spark we want to submit main.py as our job file and the rest of the code as a --py-files extra dependency jobs.zipfile.
So, out packaging script (we’ll add it as a command to our Makefile) is:

build:
    mkdir ./dist
    cp ./src/main.py ./dist
    cd ./src && zip -x main.py -r ../dist/jobs.zip .

Now we can submit our job to Spark:

make build
cd dist && spark-submit --py-files jobs.zip main.py --job wordcount

If you noticed before, out main.py code runs
sys.path.insert(0, 'jobs.zip)
making all the modules inside it available for import.
Right now we only have one such module we need to import — jobs — which contains our job logic.

We can also add a shared module for writing logic that is used by multiple jobs. That module we’ll simply get zipped into jobs.zip too and become available for import.

.
├── Makefile
├── README.md
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py
│   └── shared
│       └── __init__.py

Handling 3rd Party Dependencies

One of the requirements anyone who’s writing a job bigger the the “hello world” probably needs to depend on some external python pip packages.

To use external libraries, we’ll simply have to pack their code and ship it to spark the same way we pack and ship our jobs code.
pip allows installing dependencies into a folder using its -t ./some_folder options.

The same way we defined the shared module we can simply install all our dependencies into the src folder and they’ll be packages and be available for import the same way our jobs and shared modules are:

pip install -r requirements.txt -t ./src

However, this will create an ugly folder structure where all our requirement’s code will sit in source, overshadowing the 2 modules we really care about: shared and jobs

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

That’s why I find it useful to add a special folder — libs — where I install requirements to:

.
├── Makefile
├── README.md
├── requirements.txt
├── src
│   ├── main.py
│   ├── jobs
│   │   └── wordcount
│   │       └── __init__.py
│   └── libs
│   │   └── requests
│   │   └── ...
│   └── shared
│       └── __init__.py

With our current packaging system will break imports as import some_package will now have to be written as import libs.some_package.
To solve that we’ll simply package our libs folder into a separate zip package who’s root older is libs.

build: clean
 mkdir ./dist
 cp ./src/main.py ./dist
 cd ./src && zip -x main.py -x \*libs\* -r ../dist/jobs.zip .
 cd ./src/libs && zip -r ../../dist/libs.zip .

Now we can import our 3rd party dependencies without a libs. prefix, and run our job on PySpark using:

cd dist
spark-submit --py-files jobs.zip,libs.zip main.py --job wordcount

The only caveat with this approach is that it can only work for pure-Python dependencies. For libraries that require C++ compilation, there’s no other choice but to make sure they’re pre-installed on all nodes before the job runs which is a bit harder to manage. Fortunately, most libraries do not require compilation which makes most dependencies easy to manage,

Writing a PySpark Job

The next section is how to write a jobs’s code so that it’s nice, tidy and easy to test.

Providing a Shared Context

When writing a job, there’s usually some sort of global context we want to make available to the different transformation functions.
Spark broadcast variables, counters, and misc configuration data coming from command-line are the common examples for such job context data.

For this case we’ll define a JobContext class that handles all our broadcast variables and counters:

from collections import OrderedDict
from tabulate import tabulateclass JobContext(object):
  def __init__(self, sc):
    self.counters = OrderedDict()
    self._init_accumulators(sc)
    self._init_shared_data(sc)  def _init_accumulators(self, sc):
    pass  def _init_shared_data(self, sc):
    pass  def initalize_counter(self, sc, name):
    self.counters[name] = sc.accumulator(0)  def inc_counter(self, name, value=1):
    if name not in self.counters:
      raise ValueError("%s counter was not initialized. (%s)" % (name, self.counters.keys()))    self.counters[name] += value  def print_accumulators(self):
    print 'aa\n' * 2
    print tabulate(self.counters.items(), 
                   self.counters.keys(), 
                   tablefmt="simple")

We’ll create an instance of it on our job’s code and pass it to our transformations.
For example, let’s say we want to test the number of words on our wordcount job:

class WordCountJobContext(JobContext):
  def _init_accumulators(self, sc):
    self.initalize_counter(sc, 'words')def to_pairs(context, word):
  context.inc_counter('words')
  return word, 1def analyze(sc):
  print "Running wordcount"
  context = WordCountJobContext(sc)
  text = " ...  some text ..."  words = sc.parallelize(text.split())
  pairs = words.map(lambda word: to_pairs(context, word))
  ordered = counts.sortBy(lambda pair: pair[1], ascending=False)
  print ordered.collect()
  context.print_accumulators()

Besides sorting the words by occurrence, we’ll now also keep a distributed counter on our context that counts the number of words we processed in total. We can then nicely print it at the end by calling `context.print_accumulators()` or access it via context.counters['words']

Writing Transformations

The code above is pretty cumbersome to write instead of simple transformations that look like pairs = words.map(to_pairs) we now have this extra context parameter requiring us to write a lambda expression: pairs = words.map(lambda word: to_pairs(context, word)

So we’ll use functools.partial to make our code nicer:

def analyze(sc):
  print "Running wordcount"
  context = WordCountJobContext(sc)
  text = " ...  some text ..."  to_pairs_step = partial(to_pairs, context)  words = sc.parallelize(text.split())
  pairs = words.map(to_pairs_step)
  ordered = counts.sortBy(lambda pair: pair[1], ascending=False)
  print ordered.collect()
  context.print_accumulators()

Unit Testing

When looking at PySpark code, there are few ways we can (should) test our code:

Transformation Tests — since transformations (like our to_pairs above) are just regular Python functions, we can simply test them the same way we’d test any other python Function

from mock import MagicMock
from jobs.wordcount import to_pairsdef test_to_pairs():
  context_mock = MagicMock()
  result = to_pairs(context_mock, 'foo')
  assert result[0] == 'foo'
  assert result[1] == 1
  context_mock.inc_counter.assert_called_with('words')

These tests cover 99% of our code, so if we just test our transformations we’re mostly covered.

Entire Flow Tests — testing the entire PySpark flow is a bit tricky because Spark runs in JAVA and as a separate process.
The best way to test the flow is to fake the spark functionality.
The PySparking is a pure-Python implementation of the PySpark RDD interface.
It acts like a real Spark cluster would, but implemented Python so we can simple send our job’s analyze function a pysparking.Contextinstead of the real SparkContext to make our job run the same way it would run in Spark.
Since we’re running on pure Python we can easily mock things like external http requests, DB access etc. which is necessary for writing good unit tests.

import pysparkling
from mock import patch
from jobs.wordcount import analyze@patch('jobs.wordcount.get_text')
def test_wordcount(get_text_mock):
  get_text_mock.return_value = "foo bar foo"
  sc = pysparkling.Context()
  result = analyze(sc)
  assert result[0] == ('foo', 2)
  assert result[1] == ('bar', 1)

Testing the entire job flow requires refactoring the job’s code a bit so that analyze returns a value to be tested and that the input is configurable so that we could mock it.

Where to go from here…

You can find the full source code for a PySpark starter boilerplate implementing the concepts described above on https://github.com/ekampf/PySpark-Boilerplate

 

[출처] https://developerzen.com/best-practices-writing-production-grade-pyspark-jobs-cb688ac4d20f#.wg3iv4kie

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86398
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78835
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95598
46 [데이터분석 & 데이터 사이언스] 수많은 데이터 사이언티스트들이 직장을 떠나는 이유는 무엇인가? file 졸리운_곰 2025.03.09 903
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 1608
41 [dataset] (한글) 욕설 감지 데이터셋 file 졸리운_곰 2021.05.12 1559
40 [데이터분석][python] Dash를 사용하는 초보자 및 기타 모든 사용자를위한 Python의 대시 보드 file 졸리운_곰 2021.04.14 1763
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 782
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 1319
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