【问题标题】:Query from dynamic project+dataset+table names Google BigQuery从动态项目+数据集+表名查询 Google BigQuery
【发布时间】:2019-09-03 10:02:32
【问题描述】:

我需要对我在 BigQuery 中的所有项目执行单个查询。项目列表可能每天都在增加,所以我需要动态地完成这项工作。我需要查询的所有表共享相同的架构,但每个表都位于具有不同数据集名称的不同项目中。

我想创建一个表来保存我需要查询的所有 project.dataset.table。然后我可以执行一个查询,在“from”中我可以从提到的表中获取位置。

但实际上我不知道该怎么做。或者,如果我可以实施其他解决方案...

【问题讨论】:

    标签: google-bigquery bigquery-standard-sql


    【解决方案1】:

    如果您对多个帐户运行查询,则必须以某种方式明确指定这些帐户及其在某个集中位置的凭据。

    假设您可以为每个帐户创建独立的服务帐户 JSON,那么您只需拥有一个可以为您完成这项工作的本地脚本。一般来说,该脚本真正需要做的就是在运行查询之前检查帐户并重置环境变量GOOGLE_APPLICATION_CREDENTIALS 以指向特定帐户。

    例如,如果你使用 Python,那么大致是这样的:

    import os
    from google.cloud import bigquery
    
    accounts = [
       {
          "account_name": "xyz", 
          "credentials_json": "/path/to/xyz/credentials.json", 
          "dataset_name": "dataset", 
          "table_name": "table_name"
       },
       {
          "account_name": "xyz", 
          "credentials_json": "/path/to/xyz/credentials.json", 
          "dataset_name": "dataset", 
          "table_name": "table_name"
       }
    ]
    
    generic_query = '''
       select * from `{dataset_name}.{table_name}` where 1=1;
    '''
    
    def worker(account_info):
       '''
       your worker function which takes an account_info and runs the query.
       '''
       # set the credentials file env variable based on the account info
       os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = account_info.get("credentials_json")
       client = bigquery.Client()
       query = generic_query.format(dataset_name = account_info.get("dataset_name"), table_name = account_info.get("table_name"))
       query_job = client.query(query)
       rows = query_job.result()
       for row in rows:
          print(account_info.get("account_name"), row)
       return
    
    
    if __name__ == "__main__":
       #--run through your accounts and submit to the worker
       while accounts:
          account_info = accounts.pop(0)
          worker(account_info)
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多