1

I am trying to query my BigQuery database using Python but every time I run this code I get an error saying "No query found" even though the query works fine on Google Cloud Console.

Note: myfilepath.json and my-project-id are valid values in the code I have.

def explicit():
    import os
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "myfilepath.json"
    credentials = GoogleCredentials.get_application_default()
    bigquery_service = build('bigquery', 'v2', credentials=credentials)
    query_request = bigquery_service.jobs()

    query_data = {
        'query': ('#standardSQL SELECT * FROM `SentimentAnalysis.testdataset`')
    }

    query_response = query_request.query(
        projectId='my-project-id',
        body=query_data).execute()
    print(query_response)

explicit()

The error I get every time is:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/bigquery/v2/projects/my-project-id/queries?alt=json returned "1.58 - 1.58: No query found.">
3
  • 1
    remove #standardSQL from query and see what will happen :o) Commented Feb 2, 2018 at 16:32
  • It returns "Invalid table name: SentimentAnalysis.testdataset [Try using standard SQL] Commented Feb 2, 2018 at 16:33
  • 1
    exactly! I hoped this small exercise will give you an idea. so what was happenning before is the whole query was treated as a one string starting with # which made it a comment. do now you should just set respective property to standardSQL. Something like - query_request.use_legacy_sql = False Commented Feb 2, 2018 at 16:53

1 Answer 1

2

Working snippet based on Mikhail's advice using 'useLegacySql': False:

from apiclient.discovery import build

def explicit():
    bigquery_service = build('bigquery', 'v2')

    query_request = bigquery_service.jobs()

    query_data = {
        'query': ('SELECT * FROM `dataset.table`'),
        'useLegacySql': False
    }

    query_response = query_request.query(
        projectId='PROJECT_ID',
        body=query_data).execute()
    print(query_response)

explicit()

Alternatively, you can use the idiomatic client:

from google.cloud import bigquery

client = bigquery.Client()

QUERY = ("""
    SELECT * FROM `project.dataset.table`
    LIMIT 10""")

query_job = client.query(QUERY)

results = query_job.result()
rows = list(results)

for row in rows:
    print row
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.