ruby-on-railssphinxthinking-sphinx

Conditions for some indexes of the Thinking Sphinx


How use conditions for some Thinking Sphinx indexes? For some reasons I needed a condition like this:

...

has values(:id), **where(this_value.type_id => 1)**
has values(:id), **where(this_value.type_id => 2)**

Solution

  • To do something like this, you need to get your hands dirty with a bit of SQL. There are some concatenation commands that depend on what database you're using... first, here's an example for PostgreSQL:

    has "array_to_string(array_remove(array_agg(CASE WHEN values.type_id = 1 THEN values.id ELSE NULL END CASE), NULL), ',')",
      :as => :first_value_ids, :type => :integer, :multi => true
    

    In MySQL, it could look more like this:

    has "GROUP_CONCAT((CASE WHEN values.type_id = 1 THEN values.id ELSE NULL END CASE) SEPARATOR ',')",
      :as => :first_value_ids, :type => :integer, :multi => true
    

    If you're not yet using Thinking Sphinx v3, then the options should become :as => :first_value_ids, :type => :multi.

    These queries haven't been tested, and I'd recommend confirming they work properly, but the theory is sound.

    Also, if you're not using the values association anywhere else in your index definition in a normal manner, you'll need to ensure there's a join with the following within your index definition:

    join values