我正在尝试使用 Golang 为 Google 数据存储中的单个属性保存多个值。
我有一片 int64,我希望能够存储和检索它。从文档中我可以看到通过实现 PropertyLoadSaver{} 接口(interface)支持这一点。但我似乎无法想出正确的实现方式。
本质上,这就是我想要完成的:
type Post struct {
Title string
UpVotes []int64 `json:"-" xml:"-" datastore:",multiple"`
DownVotes []int64 `json:"-" xml:"-" datastore:",multiple"`
}
c := appengine.NewContext(r)
p := &Post{
Title: "name"
UpVotes: []int64{23, 45, 67, 89, 10}
DownVotes: []int64{90, 87, 65, 43, 21, 123}
}
k := datastore.NewIncompleteKey(c, "Post", nil)
err := datastore.Put(c, k, p)
但没有“数据存储:无效的实体类型”错误。
最佳答案
AppEngine 默认支持多值属性,您无需执行任何特殊操作即可使其正常工作。您不需要实现 PropertyLoadSaver
接口(interface),也不需要任何特殊的标记值。
如果一个struct字段是slice类型,那么它会自动成为一个多值属性。此代码有效:
type Post struct {
Title string
UpVotes []int64
DownVotes []int64
}
c := appengine.NewContext(r)
p := &Post{
Title: "name",
UpVotes: []int64{23, 45, 67, 89, 10},
DownVotes: []int64{90, 87, 65, 43, 21, 123},
}
k := datastore.NewIncompleteKey(c, "Post", nil)
key, err := datastore.Put(c, k, p)
c.Infof("Result: key: %v, err: %v", key, err)
当然,如果你愿意,你可以为 json 和 xml 指定标签值:
type Post struct {
Title string
UpVotes []int64 `json:"-" xml:"-"`
DownVotes []int64 `json:"-" xml:"-"`
}
注意事项:
但请注意,如果属性被索引,多值属性不适合存储大量值。这样做将需要许多索引(许多写入)来存储和修改实体,并且您可能会达到实体的索引限制(有关更多详细信息,请参阅 Index limits and Exploding indexes)。
例如,您不能使用多值属性来存储对 Post
的数百个赞成票和反对票。为此,您应该将投票存储为链接到 Post
的单独/不同实体,例如通过 Post
的 Key
或者最好只是它的 IntID
。
关于google-app-engine - App Engine 数据存储区 : How to set multiple values on a property using golang?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859001/