在Golang中使用Google Datastore查询具有任意键的数组。

huangapple go评论77阅读模式
英文:

Querying with an array of arbitrary keys on Google datastore in Golang

问题

从这个问题继续:

https://stackoverflow.com/questions/29202516/doing-a-in-array-query-on-google-app-engine-datastore-with-golang/29204370#29204370

现在,我正在按照之前问题中的建议,使用一个键/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, &quot;Category&quot;, &quot;&quot;, id, nil))
}

categories := make([]Category, len(keys))
err := datastore.GetMulti(c, keys, categories)
if err != nil {
	return nil, err
}

for i := 0; i &lt; 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

huangapple
  • 本文由 发表于 2015年3月28日 00:42:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/29305850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定