英文:
Querying with an array of arbitrary keys on Google datastore in Golang
问题
从这个问题继续:
现在,我正在按照之前问题中的建议,使用一个键/ID数组ids []int64
进行查询。这些ID可能实际上存在,也可能不存在(它们已被删除,但其他实例上的引用尚未被删除)。
我尝试获取这些实例的方法如下:
var keys []*datastore.Key
for _, id := range ids {
keys = append(keys, datastore.NewKey(c, "Category", "", id, nil))
}
categories := make([]Category, len(keys))
err := datastore.GetMulti(c, keys, categories)
if err != nil {
return nil, err
}
for i := 0; i < len(categories); i++ {
categories[i].Id = keys[i].IntID()
}
然而,它抛出错误:
datastore: no such entity
另一方面,我可以逐个获取每个实例,但是否有更高效的方法来处理这个问题?
英文:
A continuation from this question:
> https://stackoverflow.com/questions/29202516/doing-a-in-array-query-on-google-app-engine-datastore-with-golang/29204370#29204370
Right now, I am following the suggestion from the previous question on querying with an array of keys/ids ids []int64
. These IDs may or may not actually exist (they have been deleted, but the reference on other instances have not been removed).
My method of trying to obtain these instances looks like so:
var keys []*datastore.Key
for _, id := range ids {
keys = append(keys, datastore.NewKey(c, "Category", "", id, nil))
}
categories := make([]Category, len(keys))
err := datastore.GetMulti(c, keys, categories)
if err != nil {
return nil, err
}
for i := 0; i < len(categories); i++ {
categories[i].Id = keys[i].IntID()
}
However, it errors out throwing me:
datastore: no such entity
I could on the other hand grab each one individually, but is there a more efficient way to approach this?
答案1
得分: 2
你需要将错误断言为appengine.MultiError
类型。这样你就可以访问每个实体的错误。
if me, ok := err.(appengine.MultiError); ok {
for i, e := range me {
// 如果实体i失败,e != nil
}
} else {
// 其他错误(超时等)
}
请参考这里的MultiError文档。
英文:
You need to type assert the error to an appengine.MultiError. This way you can get access to the errors for an individual entity.
if me, ok := err.(appengine.MultiError); ok {
for i, e := range me {
// e != nil if entity i failed
}
} else {
// something else went wrong (timeout, etc).
}
See the docs for MultiError here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论