Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from lafave/gist:6e3acbce1e1434fd0fe7
Created June 22, 2014 21:56
Show Gist options
  • Save kivanio/296bbb4e9a72b227a350 to your computer and use it in GitHub Desktop.
Save kivanio/296bbb4e9a72b227a350 to your computer and use it in GitHub Desktop.
# /app/models/item.rb
class Item < ActiveRecord::Base
include ItemSearch
...
end
# /app/models/concerns/item_search.rb
module ItemSearch
extend ActiveSupport::Concern
module ClassMethods
def self.search(query_string, opts = {})
# Build the query
search_body = Jbuilder.encode do |json|
json.query do
json.filtered do
json.query do
json.multi_match do
json.fields %i(description title)
json.query query_string
end
end
json.filter do
json.bool do
json.set! :must, [
{
:term => {
:approved => true
}
}
]
end
end
end
end
end
# Execute the query
results = MyApp::Elasticsearch.client.search \
:body => search_body,
:index => :my_index,
:type => :items
# Format the results
Hashie::Mash.new(results["hits"]).hits
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment