确定 ActiveRecord 在查找过程中是否使用了索引?

sli*_*000 3 activerecord ruby-on-rails

有什么办法using the console可以确定数据库查找是否使用了索引?

例子: User.where(name: 'Bob', state: 'Delaware').first

有没有办法确定是否使用索引来快速找到它?

我添加了索引,但想验证它们是否用于某些查找。

谢谢

Bru*_*ank 7

你可以用这个检查:

User.where(name: 'Bob', state: 'Delaware').explain
Run Code Online (Sandbox Code Playgroud)

请记住,索引并不总是使查询更快,在某些情况下,索引可能会使查询运行得更慢,而某些数据库会尝试识别这一点,甚至可能也不会使用此索引。

检查索引的基数:

https://www.lullabot.com/articles/slow-queries-check-the-cardinality-of-your-mysql-indexes

小心!

http://edgeguides.rubyonrails.org/active_record_querying.html#running-explain