简体   繁体   中英

Sunspot / Solr full text search - how to index Rails associations

Is it possible to index through an association with Sunspot?

For example, if a Customer has_many Contacts, I want a 'searchable' block on my Customer model that indexes the Contact#first_name and Contact#last_name columns for use in searches on Customer.

acts_as_solr has an :include option for this. I've simply been combining the associated column names into a text field on Customer like shown below, but this doesn't seem very flexible.

searchable do
text :organization_name, :default_boost => 2
text :billing_address1, :default_boost => 2
text :contact_names do
  contacts.map { |contact| contact.to_s }
end

Any suggestions?

That's exactly how to do it. Solr is essentially document-oriented, so any data that comes from associations in your database is flattened down into your document. An :include option is just mild sugar which ends up doing the same thing that you do here.

Sure:

searchable do
  string :sort_contact_name do
    contacts.map { |contact| contact.last_name }.sort.first
  end
end

Then you can sort by the :sort_contact_name field. Note that I had to reduce the set of contact names to a single name, as Solr can only sort on fields that have a single value per document (which makes sense when you think about it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM