Search code examples
ruby-on-railsthinking-sphinx

Thinking sphinx results based on model preference


I have two models: 'A' and 'B', and want to search objects from both of them using Thinking sphinx, but I want all results of model 'A' first and then 'B'. How can I do that? I pass the following options to sphinx query

{:match_mode=>:extended, :sort_mode=>:extended, :star=>true, :order=>"@relevance DESC", :ignore_errors=>true, :populate=>true, :per_page=>10, :retry_stale=>true, :classes => [A,B]}

And then get search results using:

ThinkingSphinx.search "*xy*", options

But it gives results in mixed ordering, whereas I need all 'A' objects first. How can I do that?


Solution

  • The easiest way is to add an attribute to both models' indices:

    has "1", :as => :sort_order, :type => :integer
    

    The number within the string should be different per model. And then your :order argument becomes:

    :order => 'sort_order ASC, @relevance DESC'