-->

solr sunspot - searching belongs_to association

2019-01-19 23:09发布

问题:

I have a fabrics model that belongs to multiple other tables.

class Fabric < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :design
  belongs_to :composition
  belongs_to :collection
  belongs_to :style
  belongs_to :origin
  belongs_to :texture
  belongs_to :supplier
  has_and_belongs_to_many :colours

  searchable do
    text :name, :boost => 5 
    text :description
    text :composition do
      composition.name
   end
    text :collection do
      collection.name
    end
   text :style do
     style.name
   end
   text :origin do
     origin.name
   end
   text :texture do
     texture.name
  end
   text :supplier do
      supplier.name
  end
  end
  end

I have setup all of the reverse associations (Has_many) etc. However I do not seem to be able to get the fulltext search to query the name fields of all of these associated tables.

Any help would be greatly appreciated.

 @search = Fabric.search do
    fulltext params[:search]
  end
  @fabrics = @search.results

Ross

回答1:

You need to pass block inside your fulltext to specify which fields you want to search on.

@search = Fabric.search do
  fulltext params[:search] do
    fields(:collection, :style, :origin)
  end
  .....
end

Here is how you index in your searchable block. Solr thinks in terms of document. It doesn't care it's an association or not.

searchable do 
  text :collection do 
    collection.text 
  end
end

Then reindex.

Check this out for more detail https://github.com/sunspot/sunspot#full-text

https://github.com/sunspot/sunspot#setting-up-objects



回答2:

In case some association can be nil, do not forget to test for that otherwise you will get error while rebuilding index

text :collection do 
  collection.name if collection
end


回答3:

It looks like you haven't reindexed data after model update.

Run this command to reindex:

bundle exec rake sunspot:solr:reindex