python - 在 App Engine NDB 模型中,是否需要显式缓存对相关模型的引用以最小化查询成本并优化性能?

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

App Engine documentation on NDB caching表示默认启用缓存:

NDB automatically caches data that it writes or reads (unless an application configures it not to).

我希望这意味着我可以依靠它以经济高效且高性能的方式管理关键相关模型。这是一个涉及两个具有一对多关系的模型的简单示例。

用户模型(有很多评论):

class User(ndb.Model):
    name                    = ndb.StringProperty(required=True)
    email                   = ndb.StringProperty(required=True)

    def comments(self, limit=25):
        return UserComment.query(UserComment.user_key == self.key) \
                          .order(-UserComment.created_at) \
                          .fetch(limit)

评论模型(每条评论属于一个用户):

class UserComment(ndb.Model):
    user_key                = ndb.KeyProperty(required=True)
    text                    = ndb.StringProperty(required=True)
    created_at              = ndb.DateTimeProperty(auto_now_add=True)

    @property
    def user(self):
        return self.user_key.get()

还有一个显示评论的模板,其中包含两个对 comment.user 的引用:

<div class="comment">
  <div class="body">
    {{ comment.text }}
  </div>
  <div class="footer">
    by {{ comment.user.name }} ({{ comment.user.email }})
  </div>
</div>

这是一个正常的模式吗?对 comment.user.namecomment.user.email 的每个引用都会产生单独的 query cost或者可以信任自动 NDB 缓存来避免或最小化这种情况吗?

同样,使用User.comments方法,自动缓存是否可以信任并最大限度地降低成本?或者是否建议添加显式使用内存缓存的代码?

最佳答案

NDB 缓存涵盖实体本身。从您提到的文档中:

NDB automatically caches data that it writes or reads (unless an application configures it not to). Reading from cache is faster than reading from the Datastore.

这意味着默认情况下,您不需要为直接键/属性查找(例如 comment.user.namecomment.user.email)手动处理缓存。 code>,ndb 会处理这个问题。

但是查询则不同 - 无法知道查询返回的数据是否仍然是稍后重复的同一查询的有效响应 - 同时可能已创建其他数据。缓存查询结果是 the documentation 中提到的第一个 memcache 使用。 :

One use of a memory cache is to speed up common datastore queries. If many requests make the same query with the same parameters, and changes to the results do not need to appear on the web site right away, the app can cache the results in the memcache. Subsequent requests can check the memcache, and only perform the datastore query if the results are absent or expired. Session data, user preferences, and any other queries performed on most pages of a site are good candidates for caching.

换句话说,您应该尝试手动缓存诸如 User.comments 之类的内容,这些内容依赖于查询返回值。

关于python - 在 App Engine NDB 模型中,是否需要显式缓存对相关模型的引用以最小化查询成本并优化性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521067/

相关文章:

google-app-engine - 对 GAE 数据存储的直观理解

java - 写入 CSV 文件,然后在 Appengine (Java) 中将其压缩

python - Python中此问题的时间复杂度是多少?

python - 三角形 Numpy 切片

python - 在 django admin 中仅按年份过滤

google-app-engine - 如何在appengine仪表板中查看最新日志?

google-app-engine - 当代码在本地开发服务器上工作时,为什么 GAE 返回服务器错误?

google-app-engine - 谷歌应用引擎中的数据库设计

python - GAE blobstore - 以编程方式上传文件

python - PySide、PysideUIC 和多重继承