pratski
pratski

Reputation: 1488

Rails: Indexing and optimizing db query

Here is the issue I am facing. I have a User model that has_one profile. 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.

The issue is that last_logged_in is an attribute of the User model, while gender is an attribute of the profile model. Is there a way I can index both last_logged_in and gender? If not, how do I optimize the query for the fastest results?

Upvotes: 0

Views: 255

Answers (3)

David Aldridge
David Aldridge

Reputation: 52356

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.

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.

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.

Upvotes: 1

Bachan Smruty
Bachan Smruty

Reputation: 5734

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)

Upvotes: 1

Mike Szyndel
Mike Szyndel

Reputation: 10592

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.

Upvotes: 1

Related Questions