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

locations is list of location ids

employee_ids is list of employee ids

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

This query return 60,000 records and takes 1 minute to complete. How can I optimize it or split it?

4

2 回答 2

2

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

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

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

于 2015-05-09T16:29:52.117 回答
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)
于 2015-10-08T04:53:22.163 回答