|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2015, Google, Inc. |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Sample for making BigQuery queries using the python sdk. |
| 17 | +
|
| 18 | +This is a command-line script that queries a public shakespeare dataset, and |
| 19 | +displays the 10 of Shakespeare's works with the greatest number of distinct |
| 20 | +words. |
| 21 | +""" |
| 22 | +# [START all] |
| 23 | +from apiclient.discovery import build |
| 24 | +from apiclient.errors import HttpError |
| 25 | + |
| 26 | +from oauth2client.client import GoogleCredentials |
| 27 | + |
| 28 | + |
| 29 | +def main(project_id): |
| 30 | + # [START build_service] |
| 31 | + # Grab the application's default credentials from the environment. |
| 32 | + credentials = GoogleCredentials.get_application_default() |
| 33 | + # Construct the service object for interacting with the BigQuery API. |
| 34 | + bigquery_service = build('bigquery', 'v2', credentials=credentials) |
| 35 | + # [END build_service] |
| 36 | + |
| 37 | + try: |
| 38 | + # [START run_query] |
| 39 | + query_request = bigquery_service.jobs() |
| 40 | + query_data = { |
| 41 | + 'query': ('SELECT TOP(corpus, 10) as title, ' |
| 42 | + 'COUNT(*) as unique_words ' |
| 43 | + 'FROM [publicdata:samples.shakespeare];') |
| 44 | + } |
| 45 | + |
| 46 | + query_response = query_request.query( |
| 47 | + projectId=project_id, |
| 48 | + body=query_data).execute() |
| 49 | + # [END run_query] |
| 50 | + |
| 51 | + # [START print_results] |
| 52 | + print('Query Results:') |
| 53 | + for row in query_response['rows']: |
| 54 | + print('\t'.join(field['v'] for field in row['f'])) |
| 55 | + # [END print_results] |
| 56 | + |
| 57 | + except HttpError as err: |
| 58 | + print('Error: {}'.format(err.content)) |
| 59 | + raise err |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + # The id of the project to run queries under. |
| 64 | + project_id = input("Enter the project ID: ") |
| 65 | + main(project_id) |
| 66 | +# [END all] |
0 commit comments