Skip to content

Instantly share code, notes, and snippets.

@jraczak
Created March 4, 2015 01:54
Show Gist options
  • Save jraczak/6bff0080e5dc2bcb6ca1 to your computer and use it in GitHub Desktop.
Save jraczak/6bff0080e5dc2bcb6ca1 to your computer and use it in GitHub Desktop.
# define search method to be used in Rails controller
def search(query=nil, options={})
options ||= {}
# setup empty search definition
@search_definition = {
query: {},
filter: {},
facets: {},
}
# Prefill and set the filters (top-level `filter` and `facet_filter` elements)
__set_filters = lambda do |key, f|
@search_definition[:filter][:and] ||= []
@search_definition[:filter][:and] |= [f]
@search_definition[:facets][key.to_sym][:facet_filter][:and] ||= []
@search_definition[:facets][key.to_sym][:facet_filter][:and] |= [f]
end
# facets
@search_definition[:facets] = search_facet_fields.each_with_object({}) do |a,hsh|
hsh[a.to_sym] = {
terms: {
field: a
},
facet_filter: {}
}
end
# query
unless query.blank?
@search_definition[:query] = {
bool: {
should: [
{ multi_match: {
query: query,
# limit which fields to search, or boost here:
fields: search_text_fields,
operator: 'and'
}
}
]
}
}
else
@search_definition[:query] = { match_all: {} }
end
# add filters for facets
options.each do |key,value|
next unless search_facet_fields.include?(key)
f = { term: { key.to_sym => value } }
__set_filters.(key, f)
end
# execute Elasticsearch search
__elasticsearch__.search(@search_definition)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment