forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpleapp.go
85 lines (71 loc) · 1.88 KB
/
simpleapp.go
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
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Command simpleapp queries the Stack Overflow public dataset in Google BigQuery.
package main
// [START bigquery_simple_app_deps]
import (
"fmt"
"io"
"log"
"os"
"cloud.google.com/go/bigquery"
"google.golang.org/api/iterator"
"golang.org/x/net/context"
)
// [END bigquery_simple_app_deps]
func main() {
proj := os.Getenv("GOOGLE_CLOUD_PROJECT")
if proj == "" {
fmt.Println("GOOGLE_CLOUD_PROJECT environment variable must be set.")
os.Exit(1)
}
rows, err := query(proj)
if err != nil {
log.Fatal(err)
}
if err := printResults(os.Stdout, rows); err != nil {
log.Fatal(err)
}
}
// query returns a slice of the results of a query.
func query(proj string) (*bigquery.RowIterator, error) {
// [START bigquery_simple_app_client]
ctx := context.Background()
client, err := bigquery.NewClient(ctx, proj)
if err != nil {
return nil, err
}
// [END bigquery_simple_app_client]
query := client.Query(
`SELECT
CONCAT(
'https://stackoverflow.com/questions/',
CAST(id as STRING)) as url,
view_count
FROM ` + "`bigquery-public-data.stackoverflow.posts_questions`" + `
WHERE tags like '%google-bigquery%'
ORDER BY view_count DESC
LIMIT 10;`)
return query.Read(ctx)
}
// [START bigquery_simple_app_print]
type StackOverflowRow struct {
URL string `bigquery:"url"`
ViewCount int64 `bigquery:"view_count"`
}
// printResults prints results from a query to the Stack Overflow public dataset.
func printResults(w io.Writer, iter *bigquery.RowIterator) error {
for {
var row StackOverflowRow
err := iter.Next(&row)
if err == iterator.Done {
return nil
}
if err != nil {
return err
}
fmt.Fprintf(w, "url: %s views: %d\n", row.URL, row.ViewCount)
}
}
// [END bigquery_simple_app_print]