我可以使用Golang将平面对象插入BigQuery中-如何将嵌套数据插入表中?
我的BigQuery模式如下所示(从示例中):
[{ "name": "kind", "mode": "nullable", "type": "string" }, { "name": "fullName", "type": "string", "mode": "required" }, { "name": "visit", "type": "record", "mode": "repeated", "fields": [ { "name": "time", "type": "timestamp", "mode": "nullable" }, { "name": "duration", "type": "integer", "mode": "nullable" } ] } ]
我的第一次插入尝试如下所示(示例):
func ExampleInsert(f string,) { jsonRow := make(map[string]bigquery.JsonValue) bq, _ := bigquery.New(client) request := new(bigquery.TableDataInsertAllRequest) rows := make([]*bigquery.TableDataInsertAllRequestRows, 1) jsonRow["kind"] = bigquery.JsonValue(kind) jsonRow["visit_duration"] = bigquery.JsonValue(duration) rows[i] = new(bigquery.TableDataInsertAllRequestRows) rows[i].Json = jsonRow bq.Tabledata.InsertAll(projectID, "visits", "visitsv4", request) ... }
哪个变平并插入没有问题。我只是在用visit_duration
但是,我需要遍历一个片段并添加到访问记录中。我试图建立一个 访问 对象(没有要测试的循环)并将其添加到行中,但它没有插入,并且我没有收到任何错误:
func ExampleInsert(f string,) { jsonRow := make(map[string]bigquery.JsonValue) bq, _ := bigquery.New(client) request := new(bigquery.TableDataInsertAllRequest) rows := make([]*bigquery.TableDataInsertAllRequestRows, 1) jsonRow["kind"] = bigquery.JsonValue(kind) visits := make([]*bigquery.TableDataInsertAllRequestRows, 1) jsonVisit := make(map[string]bigquery.JsonValue) jsonVisit["duration"] = rand.Intn(1000) visits[0] = new(bigquery.TableDataInsertAllRequestRows) visits[0].Json = jsonVisit jsonRow["visit"] = visits rows[i] = new(bigquery.TableDataInsertAllRequestRows) rows[i].Json = jsonRow bq.Tabledata.InsertAll(projectID, "visits", "visitsv4", request) _, err := Call.Do() }
- -[解] - -
如评论中所建议,我还尝试创建一个切片,然后附加访问:
var visits []bigquery.JsonValue visit := make(map[string]bigquery.JsonValue) visit["duration"] = rand.Intn(100) visits = append(visits, visit) jsonRow["visit"] = visits
我可以确认这实际上是可行的:)对于那些阅读此书的人来说,即使添加了片后它最初也不是因为我已经复制了表。这样,我也将结果弄平了。小心。
访问应该是bigquery.JsonValue我不确定您为什么使用的一部分:TableDataInsertAllRequestRows应该仅对有效载荷描述符使用一次。
bigquery.JsonValue
ps。还请确保您的架构展平