【发布时间】:2019-05-09 18:39:43
【问题描述】:
在我的 Rails 项目中,我有一个 Message 模型,并且我的数据库中有数十万条消息。它还有一个“状态”列,可以“排队”或“已交付”。
创建消息后,其状态变为“已排队”,显然created_at 字段已填充。一段时间后(我不会详细说明如何),该消息的状态将变为“已发送”。
现在,对于数十万条消息,我想按它们的传递时间对它们进行分组。换句话说,计算updated_at 和created_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