Displaying similar users

155 Views Asked by At

Is it possible using Thinking Sphinx for it to output 8 (or other specified) similar users? For example I am on a Males profile page that lives in California. Under the Similar Users section it would show 8 other Males from California. It would be a random 8, no specific order. Just the gender and state location of the current user page needs to be the same.

I understand implementing geo distance with Sphinx, curious to how to show similar results based on user information. Does someone have an example of this?

2

There are 2 best solutions below

0
pat On BEST ANSWER

You could take the geodistance approach as suggested by iMacTia - though I fear that may be overkill.

I'm presuming both state and gender are fields in your Sphinx index for users. This is in the context of your controller, where you're viewing @user and want similar users.

User.search(
  :conditions => {:state => @user.state, :gender => @user.gender}
  :without    => {:sphinx_internal_id => @user.id},
  :order      => 'RAND()',
  :per_page   => 8
)

Breaking down each of those options:

  • Filter by the appropriate state and gender
  • Don't include the current user (the model's primary key is an attribute in Sphinx named sphinx_internal_id).
  • Random order
  • Only eight results
0
iMacTia On

First of all you'll need to implement sphinx geodistance like shown here. One you have done it (let's say you did it for the User table) you can now do:

@compatible_users = User.search "keyword", :geo => [@lat, @lng],
  :with => {'@geodist' => 0.0..10_000.0}

You can use the "keyword" that you prefer. @lat and @lng are current_user coordinates, @geodist is expressed in meters (so in this case it means "from 0 to 10km"). You'll also need the condition on the gender (sorry I don't know your model fields name, but this should not be a problem if you know how to use sphinx) Once you have the collection of @compatible_users, the task is now to randomly select some of them:

n = 8 # This is the number of users you want.   

# Ruby 1.9+
@ result = @compatible_users.sample(n)

# Ruby 1.8
@ result = @compatible_users.shuffle[0...n]

And you have your compatible users in @result :)

Keep in mind that if @compatible_users.size is lower than n you will get error using shuffle and a shorter array using sample. So you could need to check it and eventually do another sphinx search with a wider @geodist