📅  最后修改于: 2022-03-11 14:46:39.581000             🧑  作者: Mango
from google.cloud import bigquery
from google.cloud import storagedef export_to_gcs():
# BQ Query to get add to cart sessions
QUERY = "SELECT
CONCAT(fullVisitorId,'.', CAST(visitId AS string)) AS sessionId,
hit.page.pageTitle AS pageTitle,
CONCAT(hit.page.hostname, hit.page.pagePath) AS pageURL,
hit.page.hostname AS hostname,
product.productSKU AS productSKU,
product.v2ProductName AS productName,
product.v2ProductCategory AS productCategory,
product.productPrice/1000000 AS productPrice,
product.productQuantity AS productQuantity
FROM
`..ga_sessions_*`,
UNNEST(hits) AS hit,
UNNEST(hit.product) AS product
WHERE
hit.eCommerceAction.action_type = '3'
AND _TABLE_SUFFIX = FORMAT_DATETIME('%Y%m%d',DATETIME_ADD(CURRENT_DATETIME(),INTERVAL -1 DAY))"
bq_client = bigquery.Client()
query_job = bq_client.query(QUERY) # API request
rows_df = query_job.result().to_dataframe() # Waits for query to finish
storage_client = storage.Client()
bucket = storage_client.get_bucket('BucketName')
blob = bucket.blob('Add_to_Cart.csv')
blob.upload_from_string(rows_df.to_csv(sep=';',index=False,
encoding='utf-8'),content_type='application/octet-stream')