Search code examples
searchthinking-sphinx

Thinking Sphinx application-wide search: filtering by an attribute that only exist in some models


I want to search on multiple models and filter by a certain attribute that some models have and some do not. I want the models with the attribute to get filtered but the ones without it to just ignore it.

Currently only the models with the attribute will return results. Is there a way to make the other models return results as well by somehow ignoring the attribute filter?


Solution

  • Found a way to do it. On the indexes of the models that do not have such an attribute, a dummy one can be created like so:

    has "0", :type => :integer, :as => :the_attribute_name
    

    Then when performing the application-wide search:

    @results = ThinkingSphinx.search(@search_term, 
      :with => {:the_attribute_name => [@the_attribute_value, 0]}
    )
    

    Btw, this assumes that a zero value is not allowed on the models that do have this attribute. If zero is a valid attribute in those model then another value (e.g. 9999999) can be used. Be aware that attributes cannot accept negative integers.