2016-07-27 99 views
1

我正在尝试使用Python API设置一个简单的Google BigQuery应用程序。我遵循快速入门指南:Google BigQuery - 正确解析Python查询

import argparse 

from googleapiclient.discovery import build 
from googleapiclient.errors import HttpError 
from oauth2client.client import GoogleCredentials 


def main(project_id): 
    print "hello" 
    # [START build_service] 
    # Grab the application's default credentials from the environment. 
    credentials = GoogleCredentials.get_application_default() 
    # Construct the service object for interacting with the BigQuery API. 
    bigquery_service = build('bigquery', 'v2', credentials=credentials) 
    # [END build_service] 

    query_request = bigquery_service.jobs() 
    query_data = { 
    'query': (
      'SELECT ticker,close1' 
      'FROM Data.data_7 ' 
      'WHERE ticker = "GTIM"' 
      'LIMIT 10') 
    } 

    query_response = query_request.query(
           projectId=project_id, 
           body=query_data).execute() 

    print('Query Results:') 
    for row in query_response['rows']: 
     print('\t'.join(field['v'] for field in row['f'])) 


main("sqlserver-1384") 

并且能够成功运行上述查询。 但是每当我将其更改为:

'query': (
      'SELECT ticker,close1' 
      'FROM Data.data_7 ' 
      'ORDER BY close1 ASC' 
      'LIMIT 10') 
    } 

我得到以下错误:

Traceback (most recent call last): 
    File "server1.py", line 57, in <module> 
    main("sqlserver-1384") 
    File "server1.py", line 50, in main 
    body=query_data).execute() 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/oauth2client/util.py", line 135, in positional_wrapper 
    return wrapped(*args, **kwargs) 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/googleapiclient/http.py", line 832, in execute 
    raise HttpError(resp, content, uri=self.uri) 
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/bigquery/v2/projects/sqlserver-1384/queries?alt=json returned "Encountered " <ID> "ASCLIMIT "" at line 1, column 54. 
Was expecting: 
    <EOF>"> 

什么毛病我的格式? 我在Google BigQuery Web控制台上运行了相同的查询,它工作正常。

谢谢

回答

3

当查询字符串被由Python语法分析器连接在一起,你留下了哪些是无效的BQ SQL字ASCLIMIT。在查询中添加ASC之后的空格,您应该可以。

{ 
    'query': (
      'SELECT ticker,close1 ' # Space at the end of this line too 
      'FROM Data.data_7 ' 
      'ORDER BY close1 ASC ' # Space at the end of this line 
      'LIMIT 10') 
} 

另外,使用三层引用的字符串写你的查询:

''' 
SELECT ticker, close1 
FROM Data.data_7 
ORDER BY close1 ASC 
LIMIT 10 
''' 

随着然后换行符将被保留。

+0

感谢您的正确回答和编辑。一旦被允许,我会尽快将其标记为正确答案。 –