Created
June 16, 2014 17:21
-
-
Save lafave/6e3acbce1e1434fd0fe7 to your computer and use it in GitHub Desktop.
query_object_concern.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /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