|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Simple application that performs a query with BigQuery.""" |
| 18 | +# [START all] |
| 19 | +# [START create_client] |
| 20 | +from google.cloud import bigquery |
| 21 | + |
| 22 | + |
| 23 | +def query_shakespeare(): |
| 24 | + client = bigquery.Client() |
| 25 | + # [END create_client] |
| 26 | + # [START run_query] |
| 27 | + query_results = client.run_sync_query(""" |
| 28 | + SELECT |
| 29 | + APPROX_TOP_COUNT(corpus, 10) as title, |
| 30 | + COUNT(*) as unique_words |
| 31 | + FROM `publicdata.samples.shakespeare`;""") |
| 32 | + |
| 33 | + # Use standard SQL syntax for queries. |
| 34 | + # See: https://cloud.google.com/bigquery/sql-reference/ |
| 35 | + query_results.use_legacy_sql = False |
| 36 | + |
| 37 | + query_results.run() |
| 38 | + # [END run_query] |
| 39 | + |
| 40 | + # [START print_results] |
| 41 | + # Drain the query results by requesting a page at a time. |
| 42 | + page_token = None |
| 43 | + |
| 44 | + while True: |
| 45 | + rows, total_rows, page_token = query_results.fetch_data( |
| 46 | + max_results=10, |
| 47 | + page_token=page_token) |
| 48 | + |
| 49 | + for row in rows: |
| 50 | + print(row) |
| 51 | + |
| 52 | + if not page_token: |
| 53 | + break |
| 54 | + # [END print_results] |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + query_shakespeare() |
| 58 | +# [END all] |
0 commit comments