2016-10-10 8 views
0

私はPythonで、Google Bigqueryで実行されるクエリの結果を変数に設定するスクリプトを用意しています(ここでは使用しないライブラリがありますが、 csvファイル):変数結果BigqueryからPythonを使用したRedshiftへのETLデータ

import httplib2 
import datetime 
import json 
import csv 
import sys 
from oauth2client.service_account import ServiceAccountCredentials 
from bigquery import get_client 


#Set DAY - 1 
yesterday = datetime.datetime.now() - datetime.timedelta(days=1) 
today = datetime.datetime.now() 

#Format to Date 
yesterday = '{:%Y-%m-%d}'.format(yesterday) 
today = '{:%Y-%m-%d}'.format(today) 


# BigQuery project id as listed in the Google Developers Console. 
project_id = 'project' 

# Service account email address as listed in the Google Developers Console. 
service_account = '[email protected]' 


scope = 'https://www.googleapis.com/auth/bigquery' 

credentials = ServiceAccountCredentials.from_json_keyfile_name('/path/to/file/.json', scope) 

http = httplib2.Http() 
http = credentials.authorize(http) 


client = get_client(project_id, credentials=credentials, service_account=service_account) 

#Synchronous query 
try: 
    _job_id, results = client.query("SELECT * FROM dataset.table WHERE CreatedAt >= PARSE_UTC_USEC('" + yesterday + "') and CreatedAt < PARSE_UTC_USEC('" + today + "') limit 1", timeout=1000) 
except Exception as e: 
    print e 

print results 

返される結果は次のようなものです:

[ 
{u'Field1': u'Msn', u'Field2': u'00000000000000', u'Field3': u'jsdksf422552d32', u'Field4': u'00000000000000', u'Field5': 1476004363.421, 
u'Field5': u'message', u'Field6': u'msn', 
u'Field7': None, 
u'Field8': u'{"user":{"field":"j23h4sdfsf345","field":"Msn","field":"000000000000000000","field":true,"field":"000000000000000000000","field":"2016-10-09T09:12:43.421Z"}}', u'Field9': 1476004387.016} 
] 

私はアマゾン赤方偏移でそれをロードする必要がありますが、この形式で私が実行することはできません生成する.jsonを使用してs3からコピーします。

Redshiftをロードするためにこのjsonを変更する方法はありますか?または.csvを直接返すのですか?私はbigqueryからこのライブラリから、またはPythonを全く知らない(私の最初のスクリプトの1つ)。

ありがとうございます!フィールドの前に 'U' を削除するには

答えて

0

results = json.dumps(results) 

次に、csvファイルにJSON変数を変換するためには、私が作成した:この後

#Transform json variable to csv 
results = json.dumps(results) 

results = json.loads(results) 

f = csv.writer(open("file.csv", "w"), delimiter='|') 

f.writerow(["field","field","field","field","field","field","field", "field", "field", "field"]) 

for results in results: 
    f.writerow([results["field"], 
      results["field"], 
      results["field"], 
       results["field"], 
      results["field"], 
      results["field"], 
      results["field"], 
      results["field"], 
      results["field"], 
      results["field"]]) 

を、私がすることができましたRedshiftにファイルをロードします。

関連する問題