Skip to content

Instantly share code, notes, and snippets.

@yannvery
Last active December 30, 2015 14:08
Show Gist options
  • Save yannvery/7839804 to your computer and use it in GitHub Desktop.
Save yannvery/7839804 to your computer and use it in GitHub Desktop.
How to use a different searchable solr configuration on an object with sunspot : In this case speaker model does not inherit from celebrity model, all validations and relations can't be used on speaker model. !! Speaker and Celebrity model are used the same table be careful when you save a Speaker item!

#How to apply 2 solr search index on same object (Celebrity)

It's apparently impossible to index twice same object with sunspot solr and 2 searchable block.

##1st idea Create another model (Speaker) that inherits the searchable's model, and apply on Speaker's model another searchable block. This configuration doesn't work because Speaker's searchable block doesn't totally override Celebrity's model block, it's possible to add index on fields that don't be indexed yet but it's impossible to delete indexed fields

##2nd Idea Create a second model (Speaker) that uses the table's first model ( Celebrity ). We can add a searchable block on Speaker and create new indexes .

Now we need to force Solr to index Speaker data when Celebrity object is saved :

#celebrity model
after_save :index_speaker

def index_speaker
    Sunspot.index! Speaker.find self.id
end

Need to be carefull with relations and validations and save data ... cause Speaker doesn't inherit from Celebrity and this can be a problem.

class Celebrity < ActiveRecord::Base
after_save :index_speaker
searchable :unless => proc {|model| model.class == Celebrity} do
boolean :is_valided, :using => :validation?
text :first_name, :boost => 2
text :family_name, :boost => 5
text :describe_you, :boost => 1
end
def self.search(params)
search = Celebrity.solr_search do
keywords params
paginate :page => 1, :per_page => 2000
end
return search.results
end
def index_speaker
Sunspot.index! Speaker.find self.id
end
end
# encoding: utf-8
class Speaker < ActiveRecord::Base
set_table_name "celebrities"
default_scope where(:speaker => true)
searchable do
text :first_name, :boost => 2
text :family_name, :boost => 5
text :small_descr, :boost => 1
text :bullet_descr, :boost => 1
end
def self.search(params)
search = Speaker.solr_search do
keywords params
paginate :page => 1, :per_page => 2000
end
return search.results
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment