I have a model named Movie
that looks like this:
class Movie < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
has_many :actors, after_add: [ lambda {|a,c| a.__elasticsearch__.index_document}],
after_remove: [ lambda {|a,c| a.__elasticsearch__.index_document}]
settings index: {number_of_shards: 1} do
mappings dynamic: 'false' do
indexes :title, analyzer: 'snowball', boost: 100
indexes :actors
end
end
def as_indexed_json(options={})
self.as_json(
include: {
actors: { only: :name}
}
)
end
end
When i do Movie.first.as_indexed_json
, I get:
{"id"=>6, "title"=>"Back to the Future ",
"created_at"=>Wed, 03 Dec 2014 22:21:24 UTC +00:00,
"updated_at"=>Fri, 12 Dec 2014 23:40:03 UTC +00:00,
"actors"=>[{"name"=>"Michael J Fox"}, {"name"=>"Christopher Lloyd"},
{"name"=>"Lea Thompson"}]}
but when i do Movie.search("Christopher Lloyd").records.first
i get: => nil
.
What changes can i make to the index to search movies associated with the searched actor?
I used
filtering query
to solve this, first I created anActiveSupport::Concern
calledsearchable.rb
, the concern looks like this:I have the above concern in the
models/concerns
directory. Inmovies.rb
I have:In
movies_controller.rb
I am doing searching on theindex
action and the action looks like this:Now when i go to
http://localhost:3000/movies?q=future&actor=Christopher
I get all records which have the word future on their title and has an actor with a name Christopher. You can have more than one filter as shown by theexpert
template of the example application templates found here .