I’m having some problem searching by group when using Sunspot.
Here is an example:
# == Schema Information
#
# Table name: movies
#
# id :integer(4) not null, primary key
# title :string(255)
class Movie < ActiveRecord::Base
has_and_belongs_to_many :actors
searchable do
text :title
integer :ages, multiple: true do
actors.map(&:age)
end
text :names, multiple: true do
actors.map(&:name)
end
end
end
# == Schema Information
#
# Table name: actors
#
# id :integer(4) not null, primary key
# name :string(255)
# age :integer(30)
class Actor < ActiveRecord::Base
has_and_belongs_to_many :movies
searchable do
integer :age
text :name
end
end
I want to find every movie that has an actor named John at age 30.
Movie.search do
with(:names).equal_to("John")
with(:ages).equal_to(30)
with(:title).equal_to("...")
# ...
end
The problem is here that it may find a movie that has two actors; one named John and one at age 30. Is there a way to somehow group this together so that the movie found have an actor named John at age 30?
The solution, just like Maurício Linhares wrote in his comment, is to go through the actors model and group by movies.
The problem is that Sunspot doesn’t support Solr 3.3 or 4.0, which is the only Solr versions that support grouping.
Here is my solution using Sunspot 1.2.1 and Solr 3.3.
In my example
movie_idis placed in the actors table, this isn’t done in my real application.Cred to alindeman for his example gist.