How can I create a new view in bigquery using the python API?

后端 未结 4 1179
北荒
北荒 2021-01-19 16:19

I have some code that automatically generates a bunch of different SQL queries that I would like to insert into the bigquery to generate views, though one of the issues that

4条回答
  •  终归单人心
    2021-01-19 16:54

    Using https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert

    Submit something like below, assuming you add the authorization

    {
      "view": {
        "query": "select column1, count(1) `project.dataset.someTable` group by 1",
        "useLegacySql": false
      },
      "tableReference": {
        "tableId": "viewName",
        "projectId": "projectName",
        "datasetId": "datasetName"
      }
    }
    

    Alternatively in Python using, assuming you have a service key setup and the environmental variable GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/key. The one caveat is that as far as I can tell this can only create views using legacy sql, and as an extension can only be queried using legacy sql, though the straight API method allows legacy or standard.

    from google.cloud import bigquery
    
    def create_view(dataset_name, view_name, project, viewSQL):
    
        bigquery_client = bigquery.Client(project=project)
    
        dataset = bigquery_client.dataset(dataset_name)
        table = dataset.table(view_name)
    
        table.view_query = viewSQL
    
        try:
            table.create()
            return True
        except Exception as err:
            print(err)
            return False
    

提交回复
热议问题