简体   繁体   English

Rails:索引和优化数据库查询

[英]Rails: Indexing and optimizing db query

Here is the issue I am facing. 这是我面临的问题。 I have a User model that has_one profile. 我有一个具有has_one配置文件的用户模型。 The query I am running is to find all users that belong to the opposite sex of the current_user and then I am sorting the results by last_logged_in time of all users. 我正在运行的查询是查找属于current_user异性的所有用户,然后按所有用户的last_logged_in时间对结果进行排序。

The issue is that last_logged_in is an attribute of the User model, while gender is an attribute of the profile model. 问题在于last_logged_in是用户模型的属性,而性别是个人档案模型的属性。 Is there a way I can index both last_logged_in and gender? 有没有办法同时索引last_logged_in和性别? If not, how do I optimize the query for the fastest results? 如果没有,如何优化查询以获得最快的结果?

add_index :users, :last_logged_in
add_index :profiles, :gender

This will speed up finding all opposite-sex users and then sorting them by time. 这将加快查找所有异性用户的速度,然后按时间对其进行排序。 You can't have cross-table indexes. 您不能有跨表索引。

I am just writing the query for that 我只是在写查询

In your User model 在您的用户模型中

def self.get_opposite_sex_users(current_user) 
  self.joins([:profile]).where("profiles.gender = ?", (current_user.profile.gender ==  'M') ? 'F' : 'M').order('users.last_logged_in DESC')
end

In your action you can call it by User.get_opposite_sex_users(current_user) 您可以通过User.get_opposite_sex_users(current_user)调用它

An index on gender is unlikely to be effective, unless you're looking for a gender that is very under-represented in the table, so index on last_logged_in and let the opposite gender be filtered out of the result set without an index. 关于性别的索引不太可能有效,除非您要查找表中代表性不足的性别,所以请在last_logged_in上建立索引,并在没有索引的情况下从结果集中过滤掉相反的性别。

It might be worth it if the columns were on the same table as an index on (gender, last_logged_in) could be used to identify exactly which rows are required, but even then the majority of the performance improvement would come from being able to retrieve the rows in the required sort order by scanning the index. 如果这些列与(gender,last_logged_in)上的索引位于同一表上,则可能值得使用,它可以用来准确地确定需要哪些行,但是即使那样,大多数性能改进也将来自能够检索到的行。通过扫描索引按所需的排序顺序排列行。

Stick to indexing the last_logged_in column, and look for an explain plan that demonstrates the index being used to satisfy the sort order. 坚持为last_logged_in列建立索引,并寻找一个说明计划,该计划说明用于满足排序顺序的索引。

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

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