|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// [START functions_hello_bigquery] |
| 16 | +// Import the Google Cloud client library |
| 17 | +const {BigQuery} = require('@google-cloud/bigquery'); |
| 18 | +const bigquery = new BigQuery(); |
| 19 | + |
| 20 | +const functions = require('@google-cloud/functions-framework'); |
| 21 | + |
| 22 | +/** |
| 23 | + * HTTP Cloud Function that returns BigQuery query results |
| 24 | + * |
| 25 | + * @param {Object} req Cloud Function request context. |
| 26 | + * @param {Object} res Cloud Function response context. |
| 27 | + */ |
| 28 | +functions.http('helloBigQuery', async (req, res) => { |
| 29 | + // Define the SQL query |
| 30 | + // Queries the public Shakespeare dataset using named query parameter |
| 31 | + const sqlQuery = ` |
| 32 | + SELECT word, word_count |
| 33 | + FROM \`bigquery-public-data.samples.shakespeare\` |
| 34 | + WHERE corpus = @corpus |
| 35 | + AND word_count >= @min_word_count |
| 36 | + ORDER BY word_count DESC`; |
| 37 | + |
| 38 | + const options = { |
| 39 | + query: sqlQuery, |
| 40 | + // Location must match that of the dataset(s) referenced in the query. |
| 41 | + location: 'US', |
| 42 | + params: {corpus: 'romeoandjuliet', min_word_count: 400}, |
| 43 | + }; |
| 44 | + |
| 45 | + // Execute the query |
| 46 | + try { |
| 47 | + const [rows] = await bigquery.query(options); |
| 48 | + // Send the results |
| 49 | + res.status(200).send(rows); |
| 50 | + } catch (err) { |
| 51 | + console.error(err); |
| 52 | + res.status(500).send(`Error querying BigQuery: ${err}`); |
| 53 | + } |
| 54 | +}); |
| 55 | +// [END functions_hello_bigquery] |
0 commit comments