简体   繁体   English

Sunspot / Solr全文搜索 - 如何索引Rails关联

[英]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. 例如,如果客户有多个联系人,我希望我的客户模型上有一个“可搜索”块,用于索引Contact#first_name和Contact#last_name列,以便在Customer上进行搜索。

acts_as_solr has an :include option for this. acts_as_solr有一个:include选项。 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. 我只是将关联的列名称组合到Customer上的文本字段中,如下所示,但这似乎不太灵活。

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. Solr本质上是面向文档的,因此来自数据库中的关联的任何数据都会平滑到您的文档中。 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. 然后,您可以按:sort_contact_name字段进行排序。 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). 请注意,我必须将联系人名称集减少为单个名称,因为Solr只能对每个文档具有单个值的字段进行排序(当您考虑它时这是有意义的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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