Auto delta parent records in ThinkingSphinx

Auto updating sphinx delta on child record updates

Thinking Sphinx is quickly becoming the de-facto rails search plugin. In the past there have been a few other plugins that gained popularity and lost it almost as quickly by either being orphaned, outdated, etc. Thinking Sphinx has a clear path and a very involved/attentive maintainer.

Thinking Sphinx is quickly becoming the de-facto rails search plugin. In the past there have been a few other plugins that gained popularity and lost it almost as quickly by either being orphaned, outdated, etc. Thinking Sphinx has a clear path and a very involved/attentive maintainer.

The way sphinx does it’s “Live Updates” is through delta indexing. This allows indices to be added without rebuilding the master index. Thinking Sphinx handles new and updated records to be added to the delta through a couple of facilities, the one I will be focusing on is the delta boolean which is added to your index definition block like so:

Class UsedVehicle < ActiveRecord::Base
  define_index do
    indexes [manufacturer, model], :as => make_and_model
    indexes :trim_level
    indexes :year
    indexes :color
    indexes :condition
    indexes :price
    
    #index relations
    indexes option_package.options, :as => :options
    indexes accessories.package, :as => :accessory_package
    
    #this is to allow for delta index updating on record modification
    set_property :delta => true
  end
  
  ...
  
end

In the example above we’re indexing option_package.options and accessories.package which are ActiveRecord relations. Thinking Sphinx will update the parent UsedVehicle records in the delta when it sees them changed, through the ‘delta’ column on UsedVehicle, but what if you’re updating the child records? Simple:

Class OptionPackage < ActiveRecord::Base
  after_update :set_parent_delta
  
  def set_parent_delta
    self.used_vehicle.update_attributes(:delta => true)
  end

  ...

end

Now you’d want to do the same to the Accessory class to get that updating also. And it’s that simple.