1

我正在尝试通过 python 更新 bigquery 中的视图。我已经能够使用以下方法创建视图;

def createView(client):
    viewDataset = 'dataset'
    viewName = 'name'
    view_ref = client.dataset(viewDataset).table(viewName)
    view = bigquery.Table(view_ref)
    view_sql = """
    select * from '{}.{}' where thing = 2
    """".format(viewDataSet, viewName)
    view.view_query = view_sql
    client.create_table(view)

(用于解释目的的代码)

这工作正常并创建了视图。然后我想运行一个更新视图定义的函数。我重用了相同的代码,但失败并显示视图已经存在的错误 - 这是有道理的。然后我在这里按照这个例子; https://cloud.google.com/bigquery/docs/managing-views

使用代码更新视图 SQL 查询。基本上我换了线

client.create_table(view)

为了

client.update_table(view)

我收到一个错误,说我没有添加 fields 属性...作为一个视图,我虽然不必这样做。

谁能告诉我使用 python 更新现有 bigquery 视图的正确方法?

干杯

4

1 回答 1

0

看!您正在使用:

"select * from '{}.{}' where thing = 2"

请注意:

from '{}.{}'

但是一个表应该被引用为:

from '{}.{}.{}'

这段代码对我有用:

from google.cloud import bigquery

if __name__ == "__main__":
    client = bigquery.Client()

    dataset_view_id= 'dataset_name'
    table_view_id = 'view_name'

    view = bigquery.Table(client.dataset(dataset_view_id).table(table_view_id))


    ##############        
    ###what was in that table? request table info
    ##############
    get_view = client.get_table(view)  # API Request

    # Display OLD view properties
    print('View at {}'.format(get_view.full_table_id))
    print('View Query:\n{}'.format(get_view.view_query))


    ##############
    #update the table:
    ##############
    sql_template = (
        'SELECT * FROM `{}.{}.{}` where disease="POLIO" ')

    source_project_id = "project_from_the_query"
    source_dataset_id = "dataset_from_the_query"
    source_table_id = "table_from_the_query"

    view.view_query = sql_template.format(source_project_id, source_dataset_id, source_table_id)

    view = client.update_table(view, ['view_query'])  # API request


    ##############
    #Now print the view query to be sure it's been updated:
    ##############    
    get_view = client.get_table(view)  # API Request

    # Display view properties
    print('\n\n NEW View at {}'.format(get_view.full_table_id))
    print('View Query:\n{}'.format(get_view.view_query))
    # [END bigquery_get_view]
于 2018-10-26T12:30:55.813 回答