简体   繁体   English

Rails + validates_overlap gem:何时向数据库添加索引?

[英]Rails + validates_overlap gem: When to add indexes to the database?

I'm using the validates_overlap gem ( https://github.com/robinbortlik/validates_overlap ) in a Rails app. 我在Rails应用程序中使用validates_overlap gem( https://github.com/robinbortlik/validates_overlap )。 Here is the Model code: 这是型号代码:

  validates :start_time, :end_time, overlap: { scope: "device_id", exclude_edges: ["start_time", "end_time"] }

And here is the SQL it triggers: 这是它触发的SQL:

SELECT  1 AS one FROM "bookings"  WHERE 
((bookings.end_time IS NULL OR bookings.end_time > '2014-04-11 13:00:00.000000') AND
(bookings.start_time IS NULL OR bookings.start_time < '2014-04-11 16:00:00.000000') AND
bookings.device_id  = 20) LIMIT 1

I just want to know if I should be adding an index in my postgres database that covers start_time, end_time and device_id, or something similar? 我只想知道是否应该在我的postgres数据库中添加一个涵盖start_time,end_time和device_id或类似内容的索引? eg something like this: 例如这样的事情:

add_index :bookings, [:device_id, :start_time, :end_time], unique: true

Adding the above index to ensure database consistency would make no sense. 添加以上索引以确保数据库一致性将毫无意义。 After all you are validating the Range AND excluding the actual edges (the unique index would check exactly the edges!). 毕竟,您要验证范围并排除实际边缘(唯一索引将精确检查边缘!)。

Adding a non unique index to speed up the validation is a good idea. 添加非唯一索引以加快验证是一个好主意。 If so you should analyze your data and app queries. 如果是这样,您应该分析数据和应用程序查询。 The easiest approach is to simply add a single index for each column. 最简单的方法是为每列简单地添加一个索引。 Postgres can still use these for the multicolumn query (see heroku devcenter ). Postgres仍然可以将它们用于多列查询(请参阅heroku devcenter )。 Only if it really matters (or you do not query the columns in other combinations) a multicolumn index is necessary. 仅在确实很重要(或您不以其他组合查询列)的情况下,才需要多列索引。 If so the device_id should be first in index Rule of thumb: index for equality first—then for ranges . 如果是这样,device_id应该在索引中排在第一位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM