Search code examples
ruby-on-rails-3thinking-sphinx

Extracting custom sorting value with ThinkingSphinx


I'm using Sphinx and ThinkingSphinx to search and sort my user records. I've written my own (fairly complex) method for Sphinx to use when sorting the results, and the resulting search code looks like so:

users = User.search('',
 :without => {:id => id},
 :select => "<long SphinxQL expression> as result_weight",
 :order => 'result_weight desc'
)

All this works fine, but I'd like to be able to see the value of this expression for each of my results, by calling users.first.result_weight or something similar.

I read a bit about ThinkingSphinx's 'Panes', which can be used to add fields to the results, but I can't figure out how to use them to add this value.

How can this be done?

Edit: Version information:

  • ThinkingSphinx 3.0.4
  • Sphinx 2.0.8
  • Rails 3.2.11
  • Ruby 1.9.2p125

Solution

  • The existing AttributesPane will give you access to this value:

    users = Users.search(
      :without => {:id => id},
      :select  => "... as result_weight",
      :order   => 'result_weight DESC'
    )
    
    users.context[:panes] << ThinkingSphinx::Panes::AttributesPane
    users.each do |user|
      puts user.sphinx_attributes['result_weight']
    end