Search code examples
ruby-on-railsthinking-sphinx

Filter indexed column based on attribute filter


I have a model 'ModelA' with a has_many relation to 'ModelB'.

ModelB has a description:text column, and a day:interger column (0-6 for weekdays).

I am indexing columns from ModelB in ModelA, so I can search through ModelA.

Excerpt from index block in ModelA:

indexes model_bs.description, as: :model_b_description
has model_bs.day, as: :model_b_day
set_property field_weights: {
    model_b_description: 10
}

I would like to do ModelA.search('some description') but filter the returned results using model_b_day, ensuring the description I am searching is on a specific day (lets say :model_b_day => 5).

I can search using with: { day: 5 }, but this will return ModelB's that match the day column, not whether the description matches the search AND on that day.

Any help would be greatly appreciated!

EDIT: I should note I am using thinking sphinx v2.0.13


Solution

  • Sphinx has no concept of key/value pairs (hashes, dictionaries, whatever you wish to call them), so it does not know that a description is tied to a day within your ModelA index - it just has a bunch of descriptions mashed together into a single string, and a bunch of days as an array of integers for each ModelA record.

    The better solution in this scenario is to search on ModelB instead:

    define_index do
      indexes description
      has day
      set_property field_weights: {description: 10}
    end
    

    That way there is the relationship between the field and attribute (as it's a single value of each per record). You could also pull in ModelA data via the association (I'm guessing there's a matching belongs_to :model_a in ModelB).