如何优化DAL web2py查询?

时间:2015-05-08 07:00:20

标签: python mysql web2py database-abstraction

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分钟才能完成。我该如何优化或分割它?

2 个答案:

答案 0 :(得分:2)

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

  • 使用limit by参数:.select(limitby=(0, X))
  • 将该查询拆分为 X
  • 使用executesql db().executesql(SELECT * FROM...)使用SQL构建查询。返回将是元组,theres不是任何Row或Rows实例并且它更快,但是你将有不能享受Row对象的好处的缺点;

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

答案 1 :(得分:0)

我发现自己是一个解决方案。

公司表有20列。 在查询中未指定要选择哪些字段,查询返回60,000条记录,每条记录包含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)