【发布时间】:2015-05-22 11:42:28
【问题描述】:
我可以使用 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
但是,我需要遍历一个切片并添加到访问记录中。我尝试构建一个 visit 对象(没有要测试的循环)并将其添加到行中,但它没有插入并且我没有收到任何错误:
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()
}
---[解决方案]----
按照 cmets 中的建议,我也尝试过创建切片,然后附加访问:
var visits []bigquery.JsonValue
visit := make(map[string]bigquery.JsonValue)
visit["duration"] = rand.Intn(100)
visits = append(visits, visit)
jsonRow["visit"] = visits
我可以确认这确实有效 :) 对于那些阅读本文的人来说,即使在添加了切片之后,它最初也没有的原因是因为我复制了表格。在这样做的过程中,我也把结果弄平了。小心。
【问题讨论】:
-
我不是Golang专家,但
visits应该是bigquery.JsonValue的映射 -
你能举个例子吗?
-
visits := make(map[string]bigquery.JsonValue) -
我不确定你为什么使用:
TableDataInsertAllRequestRows,它应该只用于有效载荷描述符一次。 -
而且您还重用了错误的
i值,i与rows不同,并且多个visits必须不同。
标签: go google-bigquery