2016-07-27 9 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 Consoleで同じクエリを実行しても問題なく動作しました。

は、クエリ文字列はPythonパーサによって連結されます場合は

答えて

3

、あなたが有効なBQのSQLない単語ASCLIMITが残っているありがとうございます。クエリにASCの後に空白を追加するとOKになります。その後、改行が保持されるように

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

{ 
    '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') 
} 

また、トリプル引用符で囲まれた文字列を使用してクエリを記述。

+0

正解ありがとうございます。私が許可されるとすぐに正解とマークします。 –

関連する問題