【问题标题】:ActiveRecord alternatives to limit due to performance issues由于性能问题而限制的 ActiveRecord 替代方案
【发布时间】:2020-01-04 14:38:20
【问题描述】:

我在对数千条记录使用 limit 时遇到性能问题。

是否有任何替代方法limit 活动记录提供或解决方法?

我的查询是Spot.where(<where_conditions>).limit(20)

我想过的一些解决方案;

  • 使用where 子句来限制记录,而不是where("created_at > ? and created_at < ?", 10.days.ago, 10.days.ago)

  • 从主要的where 查询中提取ids,然后进行附加查询以获取前20 个ids = where(<where_conditions>).order('created_at ASC').pluck(:id),然后是where(id: ids.take(20)).order('created_at ASC')。担心会有内存使用。

【问题讨论】:

  • .limit 链方法实际上转换为 sql LIMIT,所以如果您遇到性能问题,您可能需要查看数据库级别的问题。
  • 使用.explain 来检查实际花费的时间。我怀疑使用WHERE (subquery) 会比仅仅对查询应用限制更快。 where(id: ids) 实际上更糟,因为您正在执行一个额外的查询,该查询必须对数据库进行并返回。

标签: ruby-on-rails database activerecord


【解决方案1】:

考虑你的where_condition

  • where_conditionindexed 中的所有列?他们indexed 的顺序和where_condition 一样吗?

  • 如果您没有索引 where_condition 中的所有列。您可以使用deferred_join 来提高性能

【讨论】:

  • 也可以使用聚集索引
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
相关资源
最近更新 更多