【问题标题】:How can I optimize DAL web2py query?如何优化 DAL web2py 查询?
【发布时间】:2015-07-19 00:09:56
【问题描述】:
result = db((db.company.location.belongs(locations)) &
            (db.company.emp_id.belongs(employee_ids)) &
            (db.company.type.belongs(types))).select()

locations 是位置 ID 列表

employee_ids 是员工 ID 列表

types = ['General', 'office', 'e-commerce']

此查询返回 60,000 条记录,需要 1 分钟才能完成。如何优化或拆分?

【问题讨论】:

    标签: python mysql web2py database-abstraction


    【解决方案1】:

    您的 DAL 查询需要大约 1 分钟的原因是因为 .select() 方法的返回是一个 Rows 实例,其中包含 60,000 个 Row 对象。这些类的许多实例化都包含耗时和内存消耗的操作。 作为解决方案,您可以:

    • 使用 limit by 参数将查询拆分为 X 片段:.select(limitby=(0, X)) 或;
    • 使用executesql db().executesql(SELECT * FROM...) 使用SQL 构造您的查询。返回将是元组,没有任何 Row 或 Rows 实例化,而且速度更快,但您将无法享受 Row 对象的好处;

    如果以上任何一个解决了您的问题,并且您的操作非常耗时,您可以尝试将拆分解决方案与线程一起使用。

    【讨论】:

    • 感谢您的回答。能够减少时间,我也找到了一个解决方案。发布了一个新答案。
    【解决方案2】:

    我找到了自己的解决方案。

    Company 表有 20 列。 查询中没有指定选择哪些字段,查询返回60000条记录,每条记录有20个字段。

    我通过只选择那些需要的列来优化查询。

    我只需要 id 和 name。所以我将查询改为以下,现在查询只需 10 秒(之前是 60 秒):

    result = db((db.company.location.belongs(locations)) &
                (db.company.emp_id.belongs(employee_ids)) &
                (db.company.type.belongs(types))).select(db.company.id, db.company.name)
    

    【讨论】:

    • 这确实有很大的不同。根据您之前的代码,我假设您希望 db.company.ALL 作为您选择的返回表单。由于处理 DB IO 通常是最耗时的操作,因此最好只获取必要的数据。此外,如果您不关心更新的结果,您还可以考虑缓存该选择结果。 """ db((db.company.location.belongs(locations)) & (db.company.emp_id.belongs(employee_ids)) & (db.company.type.belongs(types))).select(db.company .id, db.company.name, cache=(cache.ram,3600),cacheable=True) """
    • 不确定我是否应该将其作为评论或其他答案发布:P
    猜你喜欢
    • 2013-07-17
    • 2012-02-22
    • 1970-01-01
    • 2012-05-12
    • 2015-08-27
    • 2014-05-06
    • 1970-01-01
    • 2011-01-09
    • 2014-09-02
    相关资源
    最近更新 更多