Bigquery table 到云函数中的 df(数据框)

Bigquery table to df (dataframe) in a cloud Function

我有一个大查询 table - 我想将它提取到云函数内的 pandas 数据帧中,然后在头文件中做一些更改,然后将其保存到云存储中。不幸的是我的功能不起作用,任何人都可以看到可能是什么问题。我需要使用大查询提取作业还是我的想法也有效?

import base64
import pandas as pd
from google.cloud import bigquery


def extract_partial_return(event, context):
    client = bigquery.Client()
    bucket_name = "abc_test"
    project = "bq_project"
    dataset_id = "bq_dataset"
    table_id = "Partial_Return_Table"

    sql = """
    SELECT * FROM `bq_project.bq_dataset.Partial_Return_Table`
    """
    # Running the query and putting the results directly into a df
    df = client.query(sql).to_dataframe()
    df.columns = ["ga:t_Id", "ga:product", "ga:quantity"]

    destination_uri = (
        "gs://abc_test/Exports/Partial_Return_Table.csv"
    )
    df.to_csv(destination_uri)

我的requirement.txt看起来像这样

# Function dependencies, for example:
# package>=version
google-cloud-bigquery
pandas
pyarrow

首先,这样做的想法是可以的,但是您可能想要使用专为这些目的而设计的其他产品,例如 Dataflow 或 Dataproc。

另一方面,为了完成您现在的想法,您应该注意构建 SQL 命令的方式,因为您没有使用为项目创建的变量,数据集等。同样的问题发生在桶上。此外,我认为您缺少一些依赖项(fsspec 和 gcsfs)。

曼纽尔

pyarrow 库是这里的关键

import base64
import pandas as pd
from google.cloud import bigquery

def extract_partial_return(event, context):
    client = bigquery.Client()
    sql = """
    SELECT * FROM `bq_project.bq_dataset.Partial_Return_Table`
    """
    # Running the query and putting the results directly into a df
    df = client.query(sql).to_dataframe()
    df.columns = ["ga:t_Id", "ga:product", "ga:quantity"]

    destination_uri = ("gs://abc_test/Exports/Partial_Return_Table.csv")
    df.to_csv(destination_uri)

requirement.txt

pandas
fsspec
gcsfs
google-cloud-bigquery
google-cloud-storage
pyarrow