Google App Engine - 删除直到count()<= 0 [英] Google App Engine - Delete until count() &lt;= 0

查看:127
本文介绍了Google App Engine - 删除直到count()<= 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两段代码有什么不同?

  query = Location.all(keys_only = True)
while query.count()> 0:
db.delete(query.fetch(5))

# -

而True:
query = Location.all(keys_only = True)
如果不是query.count():
break
db.delete(query.fetch(5))

它们都可以。

解决方案

从逻辑上讲,这两段代码执行同样的事情 - 它们每次删除每个位置实体,5个。



第一段代码在风格和性能方面都稍好一些。 (查询本身并不需要在每个循环中重建)。



然而,这段代码并不像它那样高效。它有几个问题:
$ b


  1. 您使用 count()但是不需要。简单地获取实体会更有效率,然后测试结果以查看是否有任何结果。

  2. 您正在进行更多往返数据存储比你需要。每个 count() fetch() delete()调用必须转到数据存储并返回。这些往返行程很慢,所以你应该尽量减少它们。您可以通过在每个循环中获取更多实体来完成此操作。

    $ b b $ b

      q = Location.all(keys_only = True)
    结果= q.fetch(500)
    结果:
    db。删除(结果)
    结果= q.fetch(500)

    编辑:看看Nick的答案 - 他解释了为什么使用查询游标可以提高代码的性能。


    What is the difference between these 2 pieces of code?

    query=Location.all(keys_only=True)
    while query.count()>0:
      db.delete(query.fetch(5))
    
    # --
    
    while True:
      query=Location.all(keys_only=True)
      if not query.count():
        break
      db.delete(query.fetch(5))
    

    They both work.

    解决方案

    Logically, these two pieces of code perform the same exact thing - they delete every Location entity, 5 at a time.

    The first piece of code is better both in terms of style and (slightly) in terms of performance. (The query itself does not need to be rebuilt in each loop).

    However, this code is not as efficient as it could be. It has several problems:

    1. You use count() but do not need to. It would be more efficient to simply fetch the entities, and then test the results to see if you got any.

    2. You are making more round-trips to the datastore than you need to. Each count(), fetch(), and delete() call must go the datastore and back. These round-trips are slow, so you should try to minimize them. You can do this by fetching more entities in each loop.

    Example:

    q = Location.all(keys_only=True)
    results = q.fetch(500)
    while results:
        db.delete(results)
        results = q.fetch(500)
    

    Edit: Have a look at Nick's answer below - he explains why this code's performance can be improved even more by using query cursors.

    这篇关于Google App Engine - 删除直到count()<= 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆