【问题标题】:Speed up database query using difference between 2 columns: created_at and updated_at使用 2 列之间的差异加速数据库查询:created_at 和 updated_at
【发布时间】:2019-05-09 18:39:43
【问题描述】:

在我的 Rails 项目中,我有一个 Message 模型,并且我的数据库中有数十万条消息。它还有一个“状态”列,可以“排队”或“已交付”。

创建消息后,其状态变为“已排队”,显然created_at 字段已填充。一段时间后(我不会详细说明如何),该消息的状态将变为“已发送”。

现在,对于数十万条消息,我想按它们的传递时间对它们进行分组。换句话说,计算updated_atcreated_at 之间的差异,并将它们分为0-3 分钟、3-5 分钟、5-10 分钟和10 分钟以上。

我目前的做法是

delivery_time_data = []
    time_intervals = [{lb: 0.0, ub: 180.0}, {lb: 180.0, ub: 300.0}, {lb: 300.0, ub: 600.0},{lb: 600.0, ub: 31*3600*24}]
    time_intervals.each_with_index do |ti, i|
      @messages = Message.where(account_id: @account.id)
                      .where(created_at: @start_date..@end_date)
                      .where(direction: 'outgoing')
                      .where(status: Message::STATUS_DELIVERED)
                      .where('status_updated_at - created_at >= ?', "#{ti[:lb]} seconds")
                      .where('status_updated_at - created_at < ?', "#{ti[:ub]} seconds")
      if i == time_intervals.count - 1
        delivery_time_data.push([i+1, "Greater than #{ti[:lb]/60.to_i} minutes", @messages.count])
      else
        delivery_time_data.push([i+1, "#{ti[:lb]/60.to_i} minutes to #{ti[:ub]/60.to_i} minutes", @messages.count])
      end

它有效。但它非常慢,当我有大约 200000 条消息时,服务器可能会崩溃。

如果我希望相当频繁地创建消息,那么在 created_at 上添加索引是否是个好主意?

谢谢。

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord indexing


    【解决方案1】:

    可能是您需要正确的索引。

    你需要索引的字段是:

    • 方向
    • 状态
    • account_id
    • created_at

    所以在迁移中添加以下索引:

    add_index :messages, [:direction, :status, :account_id, :created_at]
    

    一些数据库,包括 postgresql,可以索引表达式。为获得最佳结果,请将 (updated_at - created_at) 作为您的第五个值添加到索引中。您必须使用 SQL 而不是 rails 迁移来创建它。

    我不会担心在索引表上创建记录所增加的时间。 我只是不会担心它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      相关资源
      最近更新 更多