【问题标题】:The effect of no_cache() on querySet in MongoengineMongoengine中no_cache()对querySet的影响
【发布时间】:2019-05-04 10:32:52
【问题描述】:

在 mongoengine 的官方文档中,它说从 0.8 开始,no_cache() 被添加到 mongoengine 中。它能给我们带来什么好处? no_cache 申请的典型场景是什么?

【问题讨论】:

    标签: mongodb pymongo mongoengine


    【解决方案1】:

    这里的 Mongoengine 维护者 - 默认情况下(和历史上),mongoengine 在您迭代查询集时缓存查询集的所有结果。如果您重新迭代相同的变量,这样做的好处是不会触发查询,但缺点是将所有内容都保存在内存中。即:

    class User(Document):
        pass
    
    users = User.objects()         # users is a queryset, it didn't hit the db yet
    
    _ = [us for us in in users]    # hits the db and caches all user instances in the users object
    _ = [us for us in in users]    # does not hit the db anymore, uses the users cached data
    
    
    users = User.objects().no_cache()
    _ = [us for us in in users]    # hits the db and caches all user instances
    _ = [us for us in in users]    # hits the db again
    

    使用缓存听起来是个好主意,但实际上你很少会迭代同一个查询集 2 次,如果你迭代非常大的集合,内存消耗可能会成为一个问题。

    注意以后可能会改为默认使用no_cache版本

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 2019-09-24
      • 2018-01-19
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多