RDs
RDs

Reputation: 521

Read BQ query result without struct

Has anybody tried storing result from a query to a map? I want to able to read data from BQ tables without having the need to define a struct that matches the BQ table schema.

I have tried following https://kylewbanks.com/blog/query-result-to-map-in-golang, but I want to use a RowIterator instead of the approach in this link.

Here's the code I am struggling with:

//Removed error handling for brewity 
ctx := context.Background()
client, _ := bigquery.NewClient(ctx, ProjectID)
query := fmt.Sprintf("SELECT * FROM `%s.%s.%s` LIMIT 5;", ProjectID, DatasetId, ResourceName)
queryResult := client.Query(query)
it, _ := queryResult.Read(ctx)

for {
    row := make(map[string]bigquery.Value)
    err := it.Next(&row)
    if err == iterator.Done {
        break
    }
    if err != nil {
        fmt.Printf("Error happened")
    }}

I am not sure how to proceed after this, I would ideally like to convert the data into a JSON format.

Upvotes: 1

Views: 2410

Answers (1)

elcomendante
elcomendante

Reputation: 1161

for {
     var values []bigquery.Value
     err := it.Next(&values)
     if err == iterator.Done {
        break
     }
     if err != nil {
    // TODO: Handle error.
}
fmt.Println(values)
}

Place rows into slice as you can store a row using anything that implements the ValueLoader interface, or with a slice or map of bigquery.Value

ref: godocs bq

Upvotes: 4

Related Questions