【问题标题】:Bigquery table to df (dataframe) in a cloud FunctionBigquery 表到云中的 df(数据框)函数
【发布时间】:2021-08-14 22:58:34
【问题描述】:

我有一个 bigquery 表 - 我想将它提取到云函数内的 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)

我的 requirements.txt 看起来像这样

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

【问题讨论】:

  • “我的功能不工作”是什么意思?你期望的结果是什么?你看到了什么?

标签: google-cloud-platform google-bigquery google-cloud-functions google-cloud-storage


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    曼努埃尔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多