ruby-on-rails - 使用 PSQL 在 Rails 数据库中创建重复索引
问题描述
在我的 Rails 项目中,我想通过为它们提供适当的索引来加速数据库查询。
我有一个带有, , , ,等Message
列的模型。created_at
status_updated_at
message_type
direction
status
在某些地方,我需要运行查询 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
?
代码运行良好。但只是想知道是否有必要进行第二次迁移。
谢谢。
解决方案
由于方向是第一个索引中的第一列,因此您可能不需要额外的方向索引。如果它不是第一列,您将需要它。这并不是说 postgres 不会使用它,它甚至可能会有所帮助,因为索引将小于第一个,但收益应该很小。
postgres 是否使用索引中的 status_updated_at 和 created_at ?如果是这样,我会有些惊讶。索引方向、状态和 status_updated_at - created_at 可能会更好。
推荐阅读
- python - Matplotlib:在 y 轴上显示时间时出现问题
- c++ - 创建对象/分段错误(核心转储)
- vue.js - 如何在 vue 中更新数据自我计算?
- android - Android 虚拟设备在带有 intel haxm 的 Windows Server 2019 上运行非常缓慢
- python - 在不使用正则表达式的情况下验证员工 ID - Python
- html - 有没有办法从外部域一键强制保存下载?
- mysql - 获取每组的计数,但在每组中的 N 个结果行后停止计数
- powerbi - 当通过直接引用度量或其组件编写时,为什么计算函数会为相同的表达式给出不同的结果?
- c++ - C++ 使用模板元编程生成函数
- reporting-services - 导出到 excel 时,在 excel 预览中不显示 SSRS 页脚行(正在显示其他元素)