【问题标题】:Searching a many to many database using Google Cloud Datastore使用 Google Cloud Datastore 搜索多对多数据库
【发布时间】:2013-09-12 21:36:38
【问题描述】:

我对谷歌应用引擎很陌生。我知道谷歌数据存储不是 sql,但我试图在其中获得多对多的关系行为。正如您在下面看到的,我有 Gif 实体和 Tag 实体。我希望我的应用程序通过相关标签搜索 Gif 实体。这是我所做的;

class Gif(ndb.Model):
    author = ndb.UserProperty()
    link = ndb.StringProperty(indexed=False)

class Tag(ndb.Model):
    name = ndb.StringProperty()

class TagGifPair(ndb.Model):
    tag_id = ndb.IntegerProperty()
    gif_id = ndb.IntegerProperty()

    @classmethod
    def search_gif_by_tag(cls, tag_name)
        query = cls.query(name=tag_name)
        # I am stuck here ...

这是一个正确的开始吗?如果是这样,我该如何完成它。如果没有,怎么办?

【问题讨论】:

    标签: python-2.7 google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案1】:

    您可以使用重复属性https://developers.google.com/appengine/docs/python/ndb/properties#repeated 链接中的示例使用带有实体的标签作为示例,但对于您的确切用例将如下所示:

    class Gif(ndb.Model):
        author = ndb.UserProperty()
        link = ndb.StringProperty(indexed=False)
        # you store array of tag keys here you can also just make this
        # StringProperty(repeated=True)
        tag = ndb.KeyProperty(repeated=True)
    
        @classmethod
        def get_by_tag(cls, tag_name):
            # a query to a repeated property works the same as if it was a single value
            return cls.query(cls.tag == ndb.Key(Tag, tag_name)).fetch()
    
    # we will put the tag_name as its key.id()
    # you only really need this if you wanna keep records of your tags
    # you can simply keep the tags as string too
    class Tag(ndb.Model):
        gif_count = ndb.IntegerProperty(indexed=False)
    

    【讨论】:

    • 我应该如何在这种方法中保存标签。我很新,所以我不知道如何将 tag_name 作为它的 key.id
    • 最简单的方法是 tag = Tag.get_or_insert(tag_name) 然后将 tag.key 放入标签列表中。
    【解决方案2】:

    也许你想使用列表?如果您只需要按标签搜索 gif,我会做这样的事情。由于我不熟悉ndb,所以我正在使用db。

    class Gif(db.Model):
        author = db.UserProperty()
        link = db.StringProperty(indexed=False)
        tags = db.StringListProperty(indexed=True)
    

    这样查询

    Gif.all().filter('tags =', tag).fetch(1000)
    

    【讨论】:

      【解决方案3】:

      建立多对多关系有不同的方式。使用 ListProperties 是一种方法。如果使用 ListProperties,要记住的限制是每个实体的索引数量有限制,并且总实体大小有限制。这意味着列表中的实体数量是有限制的(取决于您是先达到索引计数还是实体大小)。见本页底部:https://developers.google.com/appengine/docs/python/datastore/overview

      如果您认为引用的数量将在此限制内起作用,那么这是一个不错的方法。考虑到您不会有成千上万的主页管理员,这可能是正确的方法。

      另一种方法是拥有一个中间实体,该实体具有对多对多双方的引用属性。这种方法可以让您扩展得更高,但是由于所有额外的实体写入和读取,这会更加昂贵。

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 2019-07-12
        • 1970-01-01
        • 2012-06-05
        • 2019-01-27
        • 1970-01-01
        • 2017-03-07
        • 2012-07-15
        • 2021-01-13
        相关资源
        最近更新 更多