首页 > 解决方案 > 使用 PSQL 在 Rails 数据库中创建重复索引

问题描述

在我的 Rails 项目中,我想通过为它们提供适当的索引来加速数据库查询。

我有一个带有, , , ,等Message列的模型。created_atstatus_updated_atmessage_typedirectionstatus

在某些地方,我需要运行查询 1 之类的查询:

Message.where(created_at: @start_date..@end_date)
                      .where(message_type: @message_types)
                      .where(direction: 'outgoing')
                      .where(status: Message::STATUS_DELIVERED)
                      .where('status_updated_at - created_at >= ?', "90 seconds")
                      .where('status_updated_at - created_at < ?', "180 seconds")

在其他一些地方,我只需要查询其中的一列,例如,简单地Message.where(direction: 'outgoing')(称为查询 2)。

对于长查询,查询 1,我创建了这个迁移以加快它:

    add_index :messages, [:direction, :status, :created_at, :status_updated_at], name: 'dashboard_delivery_time_index'

对于第二个查询,查询 2,除了上面添加的索引之外,我还创建了这个迁移:

add_index :messages, :direction, name: 'index_messages_on_direction'

由于第一次迁移已经包含了,第二次迁移是否会是多余和不必要的:direction

代码运行良好。但只是想知道是否有必要进行第二次迁移。

谢谢。

标签: ruby-on-railspostgresqlperformanceactiverecordindexing

解决方案


由于方向是第一个索引中的第一列,因此您可能不需要额外的方向索引。如果它不是第一列,您将需要它。这并不是说 postgres 不会使用它,它甚至可能会有所帮助,因为索引将小于第一个,但收益应该很小。

postgres 是否使用索引中的 status_updated_at 和 created_at ?如果是这样,我会有些惊讶。索引方向、状态和 status_updated_at - created_at 可能会更好。


推荐阅读