PySparkSQL脚本模板

PySpark模板分为shell脚本和python脚本两部分,通过shell脚本提交spark任务。

shell脚本:test_submit.sh

#!/bin/sh
source /etc/profile
source /usr/local/ods_shell/shell_config.properties
locate /bin/hive

if [ $# -eq 2 ];then
    echo "参数个数为2,使用传入参数作为处理数据时间区间"
    data_date_begin_tmp=$1
    data_date_end_tmp=$2
    data_date_begin=`date -d $data_date_begin_tmp +%Y-%m-%d`
    data_date_end=`date -d $data_date_end_tmp +%Y-%m-%d`
elif [ $# -eq 0 ];then
    echo "参数个数为0,默认处理前31天的数据"
    cur_date=`date +%Y-%m-%d`
    data_date_begin=`date -d "31 days ago $cur_date" +%Y-%m-%d`
    data_date_end=$cur_date
else
    echo "参数个数错误"
    exit 1
fi

echo "处理日期:[${data_date_begin}, ${data_date_end}]"

#提交任务到Spark集群
spark-submit \
--master yarn \
--deploy-mode client \
--driver-memory 2g \
--num-executors 2 \
--executor-memory 4g \
--executor-cores 1 \
--conf spark.dynamicAllocation.maxExecutors=5 \
--conf spark.default.parallelism=10 \
--conf spark.sql.shuffle.partitions=5 \
--conf spark.sql.adaptive.enabled=true \
--conf spark.sql.adaptive.shuffle.targetPostShuffleInputSize=134217728 \
--queue queue_name \
/path/test.py ${data_date_begin} ${data_date_end}

说明:提交参数待研究完善

python脚本:test.py

import sys
from random import random
from operator import add
from os.path import expanduser, join, abspath
import importlib
import datetime
import time
from dateutil.relativedelta import relativedelta

from pyspark.sql import SparkSession
from pyspark import SparkContext, SparkConf
from pyspark.sql import Row

import logging

logging.basicConfig(level=logging.INFO, format=" %(message)s")
logger = logging.getLogger("sparrow_qis_product_usage")

warehouse_location = abspath("/user/hive/warehouse")
sparkconf = SparkConf() \
    .setAppName("sparrow_qis_product_usage") \
    .set("spark.sql.warehouse.dir", warehouse_location)
spark = SparkSession \
    .builder \
    .config(conf=sparkconf) \
    .enableHiveSupport() \
    .getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("WARN")

spark.sql("set hive.exec.dynamic.partition.mode = nonstrict")
spark.sql("set hive.exec.dynamic.partition = true")


def product_usage_download_handler(spark, data_date_start, data_date_end):
    query_sql = """
        select
        product_id,
        (case when version_name in ('0','None','trial','-') then 'other' else version_name end) as version_name,
        (case when agent_system in ('Windows','Android','Mac OS X','iOS','Chrome OS','Windows Phone','Linux') then agent_system else 'other' end) as agent_system,
        (case when regexp_replace(regexp_replace(agent_system_version,'[a-zA-Z]+',''),'\\\\.$|\\\\s','') in ('','-')
        then 'other' else agent_system_version end) as agent_system_version,
        (case when agent_system_type in ('mobile','pc','tablet') then agent_system_type else 'other' end) as agent_system_type,
        (case when agent_browser in ('Chrome,Firefox','Edge','Safari','IE','Chrome Mobile','Opera','Mobile Safari','QQ Browser','UC Browser','Sogou Explorer','Samsung Internet','Firefox Mobile',
        'Chrome Mobile WebView','Yandex Browser') then agent_browser else 'other' end) as agent_browser,
        (case when regexp_replace(regexp_replace(agent_browser_version,'[a-zA-Z]+',''),'\\\\.$|\\\\s','') in ('','-') then 'other' else agent_browser_version end) as agent_browser_version,
        agent_is_bot,
        (case when country_code in ('','-','None') then 'other' else country_code end) as country_code,
        (case when state_code in ('','-','None') then 'other' else state_code end) as state_code,
        (case when city in ('','-','None') then 'other' else city end) as city,
        substr(download_start,1,10) as datatime
        from sqoop_import_db.bas_product_usage_download
        where substr(download_start,1,10) >='{data_date_start}' and substr(download_start,1,10) < '{data_date_end}'
        and product_id!=0
        """.format(data_date_start=data_date_start, data_date_end=data_date_end)
    df = spark.sql(query_sql)
    df.registerTempTable("product_usage_download_tmp1")

    query_sql = """
        select
        product_id,
        (case when version_name='other' then 'other'
        when size(split(version_name,'\\\\.')) >= 3 then concat(split(version_name,'\\\\.')[0], '.', split(version_name,'\\\\.')[1], '.', substr(split(version_name,'\\\\.')[2],0,1))
        when size(split(version_name,'\\\\.')) = 2 then concat(split(version_name,'\\\\.')[0], '.', split(version_name,'\\\\.')[1], '.', '0')
        when size(split(version_name,'\\\\.')) = 1 and version_name != '' then concat(split(version_name,'\\\\.')[0], '.', '0', '.', '0')
        else 'other'
        end) as version_name,
        (case when agent_system='Mac OS X' then 'Macintosh' else agent_system end) as agent_system,
        (case when agent_system_version='other' then 'other'
        when size(split(agent_system_version,'\\\\.')) >= 3 then concat(split(agent_system_version,'\\\\.')[0], '.', split(agent_system_version,'\\\\.')[1], '.', substr(split(agent_system_version,'\\\\.')[2],0,1))
        when size(split(agent_system_version,'\\\\.')) = 2 then concat(split(agent_system_version,'\\\\.')[0], '.', split(agent_system_version,'\\\\.')[1], '.', '0')
        when size(split(agent_system_version,'\\\\.')) = 1 and agent_system_version != '' then concat(split(agent_system_version,'\\\\.')[0], '.', '0', '.', '0')
        else 'other'
        end) as agent_system_version,
        (case when agent_system_type='pc' then 'desktop' else agent_system_type end) as agent_system_type,
        (case when agent_browser in ('Chrome Mobile','Chrome Mobile WebView') then 'Chrome'
        when agent_browser='IE' then 'Internet Explorer'
        when agent_browser='Mobile Safari' then 'Safari'
        else agent_browser
        end) as agent_browser,
        (case when agent_browser_version='other' then 'other'
        when size(split(agent_browser_version,'\\\\.')) >= 3 then concat(split(agent_browser_version,'\\\\.')[0], '.', split(agent_browser_version,'\\\\.')[1], '.', substr(split(agent_browser_version,'\\\\.')[2],0,1))
        when size(split(agent_browser_version,'\\\\.')) = 2 then concat(split(agent_browser_version,'\\\\.')[0], '.', split(agent_browser_version,'\\\\.')[1], '.', '0')
        when size(split(agent_browser_version,'\\\\.')) = 1 and agent_browser_version != '' then concat(split(agent_browser_version,'\\\\.')[0], '.', '0', '.', '0')
        else 'other'
        end) as agent_browser_version,
        agent_is_bot,
        country_code,
        state_code,
        city,
        count(1) as count_download,
        datatime
        from product_usage_download_tmp1
        group by product_id,version_name,agent_system,
        agent_system_version,agent_system_type,
        agent_browser,agent_browser_version,
        agent_is_bot,country_code,state_code,city,datatime
        """
    df = spark.sql(query_sql)
    df.registerTempTable("product_usage_download_tmp2")

    insert_sql = """
        insert overwrite table dws_sparrow_user_analyze.dws_qis_product_usage_download partition(datatime)
        select
        product_id,
        version_name,
        t4.id as operatingsystem_id,
        agent_system_version,
        t5.id as devicecategory_id,
        t6.id as browser_id,
        agent_browser_version,
        agent_is_bot,
        t3.country_en,
        t3.country_id,
        state_code,
        city,
        count_download,
        datatime
        from product_usage_download_tmp2 t1
        left join sqoop_import_dim.dim_country t2 on t1.country_code = t2.country
        left join sqoop_import_dim.dim_country_ods t3 on lower(t2.country_a2) = lower(t3.country_en)
        left join sqoop_import_dim.dim_ga_operatingsystem t4 on t1.agent_system = t4.operatingsystem
        left join sqoop_import_dim.dim_ga_devicecategory t5 on t1.agent_system_type = t5.devicecategory
        left join sqoop_import_dim.dim_ga_browser t6 on t1.agent_browser = t6.browser
        """
    spark.sql(insert_sql)

    insert_sql = """
        insert overwrite table dm_sparrow_user_analyze.dm_qis_product_usage_download_test partition(datatime)
        select
        product_id,
        country_id,
        operatingsystem_id,
        agent_system_version,
        devicecategory_id,
        browser_id,
        agent_browser_version,
        sum(count_download) as count_download, datatime
        from dws_sparrow_user_analyze.dws_qis_product_usage_download
        where datatime >= '{data_date_start}' and datatime < '{data_date_end}'
        group by product_id, country_id, operatingsystem_id, agent_system_version,
        devicecategory_id, browser_id,agent_browser_version, datatime
        """.format(data_date_start=data_date_start, data_date_end=data_date_end)
    spark.sql(insert_sql)


def create_table(spark):
    create_sql = """
        create table if not exists dws_sparrow_user_analyze.dws_qis_product_usage_download(
            product_id             string       comment '产品id',
            version_name           string       comment '产品版本',
            operatingsystem_id     string       comment '操作系统',
            agent_system_version   string       comment '操作系统版本',
            devicecategory_id      string       comment '访问设备类型',
            browser_id             string       comment '浏览器',
            agent_browser_version  string       comment '浏览器版本',
            agent_is_bot           tinyint      comment '是否爬虫,0表示否,1表示是',
            country_en             string       comment '国家',
            country_id             string       comment '国家id',
            state_code             string       comment '州|省',
            city                   string       comment '城市',
            count_download         int          comment '下载总数'
        )
        comment 'CBS下载总数表'
        partitioned by (datatime string)
        stored as parquet
        """
    spark.sql(create_sql)

    create_sql = """
        create table if not exists dm_sparrow_user_analyze.dm_qis_product_usage_download_test(
            product_id             string       comment '产品id',
            country_id             string       comment '国家id',
            operatingsystem_id     string       comment '操作系统',
            agent_system_version   string       comment '操作系统版本',
            devicecategory_id      string       comment '访问设备类型',
            browser_id             string       comment '浏览器',
            agent_browser_version  string       comment '浏览器版本',
            count_download         int          comment '下载总数'
            )
        comment 'CBS下载总数表'
        partitioned by (datatime string)
        stored as parquet
        """
    spark.sql(create_sql)


if __name__ == '__main__':
    data_date_start = sys.argv[1]
    data_date_end = sys.argv[2]
    create_table(spark)
    product_usage_download_handler(spark, data_date_start, data_date_end)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,752评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,100评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,244评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,099评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,210评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,307评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,346评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,133评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,546评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,849评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,019评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,702评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,331评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,030评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,260评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,871评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,898评论 2 351

推荐阅读更多精彩内容