【问题标题】:How to use subqueries in Bigquery in Datalab's api?如何在 Datalab 的 api 中使用 Bigquery 中的子查询?
【发布时间】:2017-09-28 04:47:42
【问题描述】:

我有一个关于在 Datalab 的 BigQuery 中使用子查询的问题。这是 google.datalab.bigquery.Query 特有的。我可以在 Datalab 中使用带有 %bq 命令行的子查询。

假设,我在 Datalab 中使用 %bq 作为:

%bq query --name my_table1
select col1, col2 from dataset1.table1

%bq query --subqueries my_table1
select count(col1) as some_count from my_table1 where col1 is null

%bq 以上的命令行代码可以正常工作。但是,我想使用 python Datalab API 以更编程的方式来完成它。所以在 Datalab 中,我做了:

sql_str1 = '''select col1, col2 from dataset1.table1'''

my_table1 = bq.Query(sql_str1)

sql_str2 = '''select count(col1) as some_count from my_table1 where col1 is null'''

bq.Query(sql_str2, subqueries= my_table1).execute().result()

然后,我收到错误消息:

TypeErrorTraceback (most recent call last)
<ipython-input-6-c625b8e326b9> in <module>()
----> 1 bq.Query(sql_command, subqueries=web_activity).execute().result()

/usr/local/lib/python2.7/dist-packages/google/datalab/bigquery/_query.pyc in __init__(self, sql, env, udfs, data_sources, subqueries)
     79 
     80     if subqueries:
---> 81       _expand_objects(subqueries, Query, self._subqueries)
     82     if udfs:
     83       _expand_objects(udfs, _udf.UDF, self._udfs)

/usr/local/lib/python2.7/dist-packages/google/datalab/bigquery/_query.pyc in _expand_objects(obj_container, obj_type, target_list)
     59     # and add them to the target dictionary
     60     def _expand_objects(obj_container, obj_type, target_list):
---> 61       for item in obj_container:
     62         # for a list of objects, we should find these objects in the given environment
     63         if isinstance(obj_container, list):

TypeError: 'Query' object is not iterable

但是根据http://googledatalab.github.io/pydatalab/google.datalab.bigquery.html的文档,我应该可以使用这个:

class google.datalab.bigquery.Query(sql, env=None, udfs=None, data_sources=None, subqueries=None)

我做错了什么?有什么建议吗?

【问题讨论】:

    标签: python google-bigquery google-cloud-datalab


    【解决方案1】:

    你只需要传入一个数组:

    bq.Query(sql_str2, subqueries=[my_table1]).execute().result()
    

    【讨论】:

    • 谢谢yelsayed。但是,当我尝试使用子查询列表时,我收到了另一条错误消息。所以,我回到了文档。然后,我尝试将子查询放入字典中。终于,我得到了一个成功的查询结果!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多