簡體   English   中英

使用python將歷史數據從Google雲存儲移至按日期划分的bigquery表

[英]Moving historical data from google cloud storage to date-partitioned bigquery table using python

我需要將大量的歷史數據整理到Google bigquery中的日期分區中。 它將為您划分加載日期(僅適用於當前日期),但這對歷史數據並沒有真正的幫助。 到目前為止,我所看到的唯一解決方案是使用日期標記為每個日期手動執行此操作,直到google進一步構建該工具為止。 有什么辦法嗎?

我創建了自己的管道,並將其包括在下面。 要運行它,請將這篇文章中的所有代碼塊放在一起。

import datetime
from subprocess import call

start = datetime.date( year = 2016, month = 10, day = 24)
#end = datetime.date( year = 2016, month = 10, day = 01 )
end = datetime.date.today()
file_type = ['activity', 'click', 'impression', 'rich_media']       
dataset = 'dataset_name'

波紋管腳本會將文件從一個GCS存儲桶復制到另一個。 google雙擊文件的文件名中包含創建日期,此腳本使用該創建日期來確定將文件放置在哪個日期分區。

#pull all the files into our own buckets on gcs so that we dont lose data    after 3 months
call("gsutil -m cp -r gs://bucket/path/to/mysource* gs://mybucket/path/to/mydata, shell=True)

這似乎是快速分發歷史數據的最佳方法。 我想打開單個文件,並將每一行放到正確的分區中,但是我不知道如何。

#create list of dates based on stat and end date supplied by user at begining of script
def daterange( start_date, end_date ):
    if start_date <= end_date:
        for n in range( ( end_date - start_date ).days + 1 ):
            yield start_date + datetime.timedelta( n )
    else:
        for n in range( ( start_date - end_date ).days + 1 ):
            yield start_date - datetime.timedelta( n )

我在底部添加了try / except來進行錯誤處理,但我認為它實際上沒有任何作用,因為調用永遠不會出錯,如果表名被弄亂了,則會在服務器端產生作業錯誤,但不會實際停止進程或傷害任何事情。

使用--nosync標志可以讓我將調用用於異步作業,起初我使用的是popen,但我不認為popen會自行清理(我認為call可以嗎?),因此這似乎是一個更好的選擇。

#creates a bunch of jobs to upload GCS files into GBQ partitioned tables
for bucket in file_type:
    for date in daterange( start, end ):
        date = str(date).replace('-','')
        source = 'gs://mybucket/path/to/mydata' + '*'
        table = bucket + '$' + date
        try: 
            process = call("bq --nosync load --skip_leading_rows=1 --replace  dev."\
                           + table + ' ' + source, shell=True)
        except:
            print 'missing ' + bucket + ' data for ' + date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM