【问题标题】:AppEngine Datastore Golang: Get ancestor for a query resultAppEngine Datastore Golang:获取查询结果的祖先
【发布时间】:2016-08-09 13:02:33
【问题描述】:

是否可以获取查询结果的祖先键?根据 datastore 文档 (https://cloud.google.com/appengine/docs/go/datastore/reference#Query.Run),query.Run() 结果只有 Cursor() 和 Next() 函数,两者都不会引导您找到祖先。似乎这应该是范围内的信息,除非 Datastore 的机制阻止它。是否由开发人员将祖先写入孩子的属性(具有匹配的种类)(如果我们愿意承担费用)?

【问题讨论】:

    标签: google-app-engine go google-cloud-datastore


    【解决方案1】:

    如果您的查询返回结果,则祖先包含在实体 Key 中。

    实体键由Iterator.Next()返回,例如:

    func (t *Iterator) Next(dst interface{}) (*Key, error)
    

    从key中,使用Key.Parent()方法获取祖先。

    看这个例子:

    query := datastore.NewQuery("MyEntity")
    
    e := MyEntity{}
    for i := query.Run(ctx); ; {
        if k, err = t.Next(&te); err == nil {
            log.Infof("Ancestor / parent key: %v", k.Parent())
        }
    }
    

    注意,祖先存储在datastore.Query中,但没有导出:

    type Query struct {
        ancestor *Key
        // ...
    }
    

    Query.Run()返回的datastore.Iterator包含Query,但也未导出:

    type Iterator struct {
        // q is the original query which yielded this iterator.
        q *Query
        //...
    }
    

    所以你不能访问这些结构字段,你最好的选择是结果中的一个实际实体(或者更确切地说是它的键)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多