forked from GoogleCloudPlatform/nodejs-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueries.js
More file actions
203 lines (182 loc) · 5.23 KB
/
queries.js
File metadata and controls
203 lines (182 loc) · 5.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/**
* Copyright 2017, Google, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// [START bigquery_simple_app_all]
// [START bigquery_simple_app_print]
function printResult (rows) {
console.log('Query Results:');
rows.forEach(function (row) {
let str = '';
for (let key in row) {
if (str) {
str = `${str}\n`;
}
str = `${str}${key}: ${row[key]}`;
}
console.log(str);
});
}
// [END bigquery_simple_app_print]
// [START bigquery_simple_app_query]
const sqlQuery = `SELECT
corpus, COUNT(*) as unique_words
FROM publicdata.samples.shakespeare
GROUP BY
corpus
ORDER BY
unique_words DESC LIMIT 10;`;
function queryShakespeare (projectId) {
// Imports the Google Cloud client library
const BigQuery = require('@google-cloud/bigquery');
// The project ID to use, e.g. "your-project-id"
// const projectId = "your-project-id";
// Instantiates a client
const bigquery = BigQuery({
projectId: projectId
});
// Query options list: https://cloud.google.com/bigquery/docs/reference/v2/jobs/query
const options = {
query: sqlQuery,
useLegacySql: false // Use standard SQL syntax for queries.
};
// Runs the query
bigquery
.query(options)
.then((results) => {
const rows = results[0];
printResult(rows);
})
.catch((err) => {
console.error('ERROR:', err);
});
}
// [END bigquery_simple_app_query]
// [END bigquery_simple_app_all]
function syncQuery (sqlQuery, projectId) {
// [START bigquery_sync_query]
// Imports the Google Cloud client library
const BigQuery = require('@google-cloud/bigquery');
// The project ID to use, e.g. "your-project-id"
// const projectId = "your-project-id";
// Instantiates a client
const bigquery = BigQuery({
projectId: projectId
});
// Query options list: https://cloud.google.com/bigquery/docs/reference/v2/jobs/query
const options = {
query: sqlQuery,
timeoutMs: 10000, // Time out after 10 seconds.
useLegacySql: false // Use standard SQL syntax for queries.
};
// Runs the query
bigquery
.query(options)
.then((results) => {
const rows = results[0];
console.log('Rows:');
rows.forEach((row) => console.log(row));
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END bigquery_sync_query]
}
function asyncQuery (sqlQuery, projectId) {
// [START bigquery_async_query]
// Imports the Google Cloud client library
const BigQuery = require('@google-cloud/bigquery');
// The project ID to use, e.g. "your-project-id"
// const projectId = "your-project-id";
// Instantiates a client
const bigquery = BigQuery({
projectId: projectId
});
// Query options list: https://cloud.google.com/bigquery/docs/reference/v2/jobs/query
const options = {
query: sqlQuery,
useLegacySql: false // Use standard SQL syntax for queries.
};
let job;
// Runs the query as a job
bigquery
.startQuery(options)
.then((results) => {
job = results[0];
console.log(`Job ${job.id} started.`);
return job.promise();
})
.then(() => {
console.log(`Job ${job.id} completed.`);
return job.getQueryResults();
})
.then((results) => {
const rows = results[0];
console.log('Rows:');
rows.forEach((row) => console.log(row));
})
.catch((err) => {
console.error('ERROR:', err);
});
// [END bigquery_async_query]
}
const cli = require(`yargs`)
.demand(1)
.options({
projectId: {
alias: 'p',
default: process.env.GCLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT,
description: 'The Project ID to use. Defaults to the value of the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.',
requiresArg: true,
type: 'string'
}
})
.command(
`sync <sqlQuery>`,
`Run the specified synchronous query.`,
{},
(opts) => syncQuery(opts.sqlQuery, opts.projectId)
)
.command(
`async <sqlQuery>`,
`Start the specified asynchronous query.`,
{},
(opts) => asyncQuery(opts.sqlQuery, opts.projectId)
)
.command(
`shakespeare`,
`Queries a public Shakespeare dataset.`,
{},
(opts) => queryShakespeare(opts.projectId)
)
.example(
`node $0 sync "SELECT * FROM publicdata.samples.natality LIMIT 5;"`,
`Synchronously queries the natality dataset.`
)
.example(
`node $0 async "SELECT * FROM publicdata.samples.natality LIMIT 5;"`,
`Queries the natality dataset as a job.`
)
.example(
`node $0 shakespeare`,
`Queries a public Shakespeare dataset.`
)
.wrap(120)
.recommendCommands()
.epilogue(`For more information, see https://cloud.google.com/bigquery/docs`)
.help()
.strict();
if (module === require.main) {
cli.parse(process.argv.slice(2));
}